获取订单行满足特定要求的订单

时间:2013-11-25 20:06:18

标签: sql sql-server

我有以下简化表:

tblOrders

orderID    date
---------------------
1          2013-10-04
2          2013-10-05
3          2013-10-06

tblOrderLines

lineID     orderID     ProductCategory
--------------------------------------
1          1           10
2          1           3
3          1           10
4          2           3
5          3           3
6          3           10
7          3           10

如果任何订单行有ProductCategory = 10,我想从tblOrders中选择记录。因此,如果特定订单的所有行都没有ProductCategory = 10,那么不要返回该订单。

我该怎么做?

4 个答案:

答案 0 :(得分:6)

这应该做:

SELECT *
FROM tblOrders O
WHERE EXISTS(SELECT 1 FROM tblOrderLines
             WHERE ProductCategory = 10
             AND OrderID = O.OrderID)

答案 1 :(得分:1)

试试这个

SELECT DISTINCT orderId
FROM tblOrders t1
INNER JOIN tblOrderLines t2 ON t1.orderId = t2.orderId
WHERE t2.ProductCategory = 10

答案 2 :(得分:1)

您可以使用此

的存在
Select o.*
From tblOrders o
Where exists (
    Select 1
    From tblOrderLines ol
    Where ol.ProductCategory = 10
    And ol.OrderId = o.OrderId
)

答案 3 :(得分:0)

试试这个:

SELECT *
FROM tblOrders O
    JOIN tblOrderLines L
    ON O.orderID = L.orderID
WHERE L.OrderID in (SELECT orderID FROM tblOrderLines WHERE ProductCategory = 10)