Question

I have a situation where a LEFT JOIN is not going far enough in what I need to accomplish. I have a product table (Products with columns ItemID, ProductName, Price) and an order table (Orders with columns OrderNumber, ItemID, Quantity).

I need the query to return all of the products from the Products table that are not currently a part of a specific order (for example, list all products that are not a part of OrderNumber 52).

My current query lists all of the products but excludes the products that are a part of 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";  
Was it helpful?

Solution

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

OTHER TIPS

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

What you need can be easily accomplished just by adding the order number in the join condition:

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top