查找所有没有至少一项标记为“糖果”的商品的订单

时间:2018-09-23 20:47:59

标签: sql sql-server tsql

我必须使用子查询才能找到所有糖果中至少没有一项的订单。我在子查询方面遇到了麻烦,因此我们将不胜感激。这就是我到目前为止所拥有的。

SELECT O.orderid, O.orderdate, C.custid, C.companyname
FROM Sales.Orders AS O JOIN Sales.Customers AS C ON O.custid = C.custid
JOIN Sales.OrderDetails AS D ON D.orderid = O.orderid
JOIN Production.Products AS P ON P.productid = D.productid
WHERE EXISTS
 (SELECT P.productid FROM Production.Products AS P JOIN 
Production.Categories AS CA
        ON P.categoryid = CA.categoryid JOIN Sales.OrderDetails AS D ON 
        D.orderid = O.orderid
        WHERE CA.categoryname NOT LIKE '%Confections%')

1 个答案:

答案 0 :(得分:1)

您可以简单地使用LEFT JOINWHERE

SELECT O.orderid, O.orderdate, C.custid, C.companyname
FROM Sales.Orders O JOIN
     Sales.Customers C
     ON O.custid = C.custid JOIN
     Sales.OrderDetails D 
     ON D.orderid = O.orderid JOIN
     Production.Products P
     ON P.productid = D.productid LEFT JOIN
     Production.Categories CA
     ON P.categoryid = CA.categoryid AND 
        CA.categoryname LIKE '%Confections%'
WHERE CA.CatgoryId IS NULL;

此版本假定所有订单都至少具有一种产品。这似乎是一个合理的假设。对于没有产品的订单,可以轻松调整查询。