如何发现哪些订单没有明细行?
表订单:orderId(int),customerName,deliveryDate(date),price(decimal)
表详细信息:detailId(int),orderId(int),sku(varchar),quantity(int)
我尝试过(没有成功):
SELECT
COUNT(Details.detailId) AS Tot,
Orders.orderId
FROM Details
INNER JOIN Orders
ON Details.orderId = Orders.orderId
GROUP BY Details.orderId
HAVING Tot = 0
答案 0 :(得分:4)
not in
或not exists
怎么样?
select o.*
from orders o
where not exists (select 1
from details d
where d.orderId = o.orderId
);
如果您不想要所有列,那么select
可以在外部select
中找到您想要的列。
答案 1 :(得分:0)
使用外部联接选择它,检查orderId是否为null ...像这样
SELECT
o.*
FROM orders o
LEFT OUTER JOIN details d
ON d.orderId = o.orderId
WHERE d.orderId IS NULL
答案 2 :(得分:0)
尝试使用LEFT OUTER JOIN join。另请参阅How to retrieve non-matching results in mysql。
INNER JOINS 从两个匹配的表中选择行。其他所有内容都将被丢弃,并且在您可以使用HAVING
LEFT OUTER JOINS 为左表(订单)中的每个条目选择一行。始终为右表生成一行(详细信息)。如果找不到匹配的行,则值将为NULL。我们可以利用这个优势,尝试:
SELECT Orders.orderId, Details.orderId
FROM Orders
LEFT OUTER JOIN Details -- generate a row for every row in a
-- make null if not matching
ON Details.orderId = Orders.orderId -- match condition
WHERE Details.orderId IS NULL