0

我有一种情况,LEFT JOIN 在我需要完成的事情上做得不够。我有一个产品表(Products 列 ItemID, ProductName, Price)和一个订单表(Orders 列 OrderNumber, ItemID, Quantity)。

我需要查询返回 Products 表中当前不属于特定订单的所有产品(例如,列出不属于 OrderNumber 52 的所有产品)。

我当前的查询列出了所有产品,但不包括属于 ANY OrderNumber 的产品。

$query = "SELECT Products.ItemID, Products.ProductName
FROM Products
LEFT JOIN Orders
ON Orders.ItemID = Products.ItemID
WHERE Orders.ItemID IS NULL
ORDER BY Products.ProductName";  
4

3 回答 3

1

You can use a anti-join for this purpose, like so:

SELECT ItemID, ProductName
FROM Products
WHERE ItemID NOT IN (
    SELECT ItemID
    FROM Orders
    WHERE OrderID = X
)
ORDER BY ProductName
于 2013-02-26T16:30:26.210 回答
0

只需在连接条件中添加订单号即可轻松完成您的需求:

SELECT Products.ItemID, Products.ProductName
FROM Products
LEFT JOIN Orders
ON (Orders.ItemID = Products.ItemID AND OrderNumber = 52)
WHERE Orders.ItemID IS NULL
ORDER BY Products.ProductName
于 2013-02-26T16:33:33.480 回答
0
SELECT Products.ItemID, Products.ProductName
FROM Products
WHERE Products.ItemID not in (select Orders.ItemID from Orders where Orders.OrderNumber = xxx)
ORDER BY Products.ProductName
于 2013-02-26T16:29:31.343 回答