我正在尝试加入两个表ORDER和ORDER_FLG。我想从ORDER中提取所有列,而不是将Flg作为' Y'在ORDER_FLG表中。
ORDER
Branch_nbr |Order_Id | Order_start_dt |Order_end_dt
0001 | 110000 | 01/01/2014 | 02/02/2014
0002 | 110001 | 03/03/2014 | 04/04/2014
0003 | 110002 | 05/05/2014 | 06/06/2014
ORDER_FLG
Branch_Nbr |Order_Id |Flg
0001 | 110000| Y
0003 | 110002| N
SQL:
SELECT A.*
FROM ORDER AS A LEFT JOIN ORDER_FLG AS B
ON A.Branch_nbr=B.Branch_nbr AND A.Order_Id=B.Order_Id
WHERE A.Order_start_dt >= 'SOME_DATE'
AND A.Order_end_dt <= 'SOME_DATE'
AND B.Flg <> 'Y'
我应该得到两行(110002,110001)作为输出,但我只得到一行。如果第二个表中不存在条目,则不从第一个表中提取数据。不应该从第一个表中拉出所有数据吗?
我尝试了这个,它有效但需要时间 -
SELECT A.*
FROM ORDER AS A
WHERE A.Order_start_dt >= 'SOME_DATE'
AND A.Order_end_dt <= 'SOME_DATE'
AND A.Order_Id NOT IN ( SELECT Order_Id FROM ORDER_FLG
WHERE Order_Id=A.Order_Id AND Branch_nbr=A.Branch_nbr
AND Flg='Y')
答案 0 :(得分:1)
您的where子句包含对外表的引用:
AND B.Flg <> 'Y'
在外连接之后应用where子句。来自外部联接表的任何不具有匹配项的行将在结果集中具有空值。 Null与您的约束不匹配,因此从结果集中删除行。
Try this instead:
SELECT A.*
FROM ORDER AS A LEFT JOIN ORDER_FLG AS B
ON A.Branch_nbr=B.Branch_nbr AND A.Order_Id=B.Order_Id
AND B.Flg <> 'Y'
WHERE A.Order_start_dt >= 'SOME_DATE'
AND A.Order_end_dt <= 'SOME_DATE'
答案 1 :(得分:1)
试试这个:
SELECT A.*
FROM ORDER AS A LEFT JOIN ORDER_FLG AS B
ON A.Branch_nbr=B.Branch_nbr AND A.Order_Id=B.Order_Id
WHERE A.Order_start_dt >= 'SOME_DATE'
AND A.Order_end_dt <= 'SOME_DATE'
AND (B.Flg IS NULL OR B.Flg <> 'Y' )
B.Flg&lt;&gt; &#39; Y&#39;对于在ORDER_FLG中没有匹配行的所有订单,条件显然是假的。在这些字段中得到NULL,因此必须在WHERE子句中允许这种可能性。