左外连接没有给出任何结果
Posted
技术标签:
【中文标题】左外连接没有给出任何结果【英文标题】:Left Outer Join is not giving any result 【发布时间】:2016-02-11 09:12:12 【问题描述】:我想加入包含 Portal_Order 表中的所有值以及其他表中的其他匹配值的表。 左外连接不返回值
查询:
With Max_Date As (Select Max(Change_Date) Change_Date, Ocoe_Job_Id
From Ocoe_Job_Status Where Ocoe_Job_Id In
(Select Ocoe_Job_Id From Portal_Order Where To_Char(Created_Date,'YYYY-MM-DD')
Between ( Select To_Char(Sysdate-1000,'YYYY-MM-DD') From Dual)
And ( Select To_Char(Sysdate,'YYYY-MM-DD') From Dual) )
Group By Ocoe_Job_Id)
Select Order_Id, Order_Name, Order_Desc, B.Description As Order_Status, C.Ocoe_Job_Id, C.Comments
As Communication_Id , Communication_Name, Created_By, Count(*) Over () As Total_Record_Count, Row_Number()
Over ( Order By Order_Id ) Row_Number
From Max_Date D,
Ocoeowner.Portal_Order A
Left Outer Join Ocoeowner.Ocoe_Job_Status C On C.Ocoe_Job_Id =A.Ocoe_Job_Id
LEFT OUTER JOIN Ocoeowner.Portal_Order_Status_Code_Lk B on A.Order_Status = B.Status_Code
Where To_Char(Created_Date,'YYYY-MM-DD')
Between ( Select To_Char(Sysdate-1000,'YYYY-MM-DD') From Dual) And ( Select To_Char(Sysdate,'YYYY-MM-DD') From Dual)
And C.Ocoe_Job_Id = D.Ocoe_Job_Id And D.Change_Date = C.Change_Date AND communication_name='ptuletters';
【问题讨论】:
当您使用双表(和 plsql)时,表明您使用的是 Oracle 而不是 mysql MySQL 也不支持with name as ...
,所以它似乎是一个不正确的标签
【参考方案1】:
谓词条件需要在连接的On
子句中,而不是在where 子句中。外部联接的工作方式是在分析联接条件之后,将所有与内部不匹配的“外部”行添加回......但这一切都发生在处理 where 子句之前。因此,如果 where 子句谓词从外连接的外侧过滤属性,则所有这些行将再次被删除......(它们都是空的)。将谓词放在连接条件中
And C.Ocoe_Job_Id = D.Ocoe_Job_Id And D.Change_Date = C.Change_Date
必须移动,也可能是AND communication_name='ptuletters'
,取决于源表
【讨论】:
【参考方案2】:试试这个:
WITH Max_Date AS
(SELECT MAX(Change_Date) Change_Date,
Ocoe_Job_Id
FROM Ocoe_Job_Status
WHERE Ocoe_Job_Id IN
(SELECT Ocoe_Job_Id
FROM Portal_Order
WHERE TO_CHAR(Created_Date,'YYYY-MM-DD') BETWEEN
( SELECT TO_CHAR(Sysdate-1000,'YYYY-MM-DD') FROM Dual
)
AND ( SELECT TO_CHAR(Sysdate,'YYYY-MM-DD') FROM Dual)
)
GROUP BY Ocoe_Job_Id
)
SELECT Order_Id,
Order_Name,
Order_Desc,
B.Description AS Order_Status,
C.Ocoe_Job_Id,
C.Comments AS Communication_Id ,
Communication_Name,
Created_By,
COUNT(*) Over () AS Total_Record_Count,
Row_Number() Over ( Order By Order_Id ) Row_Number
FROM
Ocoeowner.Portal_Order A LEFT OUTER JOIN Ocoeowner.Ocoe_Job_Status C ON
A.Ocoe_Job_Id=C.Ocoe_Job_Id
LEFT OUTER JOIN Ocoeowner.Portal_Order_Status_Code_Lk B ON
A.Order_Status = B.Status_Code
LEFT OUTER JOIN Max_Date D ON
C.Ocoe_Job_Id = D.Ocoe_Job_Id
AND C.Change_Date = D.Change_Date
WHERE
TO_CHAR(Created_Date,'YYYY-MM-DD') BETWEEN
( SELECT TO_CHAR(Sysdate-1000,'YYYY-MM-DD') FROM Dual
)
AND ( SELECT TO_CHAR(Sysdate,'YYYY-MM-DD') FROM Dual)
AND NVL(communication_name, 'ptuletters')='ptuletters';
【讨论】:
以上是关于左外连接没有给出任何结果的主要内容,如果未能解决你的问题,请参考以下文章