MySQL连接表,其中第二个表至少有一个用于键的NULL字段

时间:2015-12-01 11:24:05

标签: mysql join

我有两张表ordersorder_items

order_items表有一个Completion_Date字段,该字段为NULL,直到该项完成。我只想返回至少有一个具有NULL Completion_Date的项目的订单。

SELECT orders.Order_Number
  FROM orders
LEFT JOIN order_items 
   ON (orders.Order_Number = order_items.Order_Number)
WHERE order_items_Completion_Date IS NULL

如何在Order_Number键的至少一个 NULL Completion_Date字段的哪个地方加入?

2 个答案:

答案 0 :(得分:1)

您可能会发现exists为此做得更好:

select o.*
from orders o
where exists (select 1
              from order_items oi
              where oi.Order_Number = o.Order_Number and
                    oi.Completion_Date is null
             );

虽然您也可以使用join执行此操作,但如果订单包含多个NULL完成日期的项目,则该方法可能会导致重复的行。

答案 1 :(得分:0)

如果我理解正确,你只需将WHERE子句放到ON子句中就像那样:

SELECT orders.Order_Number
  FROM orders
LEFT JOIN order_items 
   ON (orders.Order_Number = order_items.Order_Number)
   AND order_items_Completion_Date IS NULL