用于查找具有相同订单行的订单的Sql查询

时间:2014-02-05 09:02:45

标签: sql oracle

如何编写可以找到具有相同订单行(详细信息)的订单的查询?

样本数据

表:订单

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并返回AD

这可以在一个查询中完成吗?

4 个答案:

答案 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

FIDDLE DEMO

答案 3 :(得分:0)

我在不使用Order表的情况下完成了所需的操作。

SELECT id from ProductT
group by id
having count(*)=3;

SQL Fiddle