如何编写可以找到具有相同订单行(详细信息)的订单的查询?
样本数据
表:订单
ORDER_ID
--------
A
B
C
D
表:OrderDetails
OrderID ProductID
------------------
A ProductX
A ProductY
A ProductZ
B ProductX
B ProductY
C ProductZ
D ProductX
D ProductY
D ProductZ
现在我想传递ProductX,ProductY,ProductZ
并返回A
和D
。
这可以在一个查询中完成吗?
答案 0 :(得分:1)
也许这样的东西是你想要的?
SELECT DISTINCT Orders.OrderID
FROM Orders
INNER JOIN OrderDetails ON Orders.OrderID = OrderDetails.OrderID
WHERE OrderDetails.ProductID IN ('ProductX', 'ProductY', 'ProductZ')
GROUP BY Orders.OrderID
HAVING COUNT(*) = 3
另请注意,Order
是保留关键字,不应用作表名。
答案 1 :(得分:0)
SELECT OrderId FROM
(SELECT DISTINCT o.OrderId, p.Product
FROM Orders o
INNER JOIN OrderDetails p
ON o.OrderId = p .OrderId
WHERE p.Product IN ('ProductX', 'ProductY', 'ProductZ') ) tab
GROUP BY OrderId
HAVING COUNT(*) = 3
答案 2 :(得分:0)
试试这个
SELECT P.OrderID
FROM Order1 P JOIN OrderDetails D ON
P.OrderID = D.OrderID
WHERE P.OrderID IN (SELECT OrderID FROM OrderDetails WHERE ProductID IN ('ProductX', 'ProductY', 'ProductZ'))
Having Count(P.OrderID)=3
GROUP BY P.OrderID
答案 3 :(得分:0)