MySQL查找包含特定产品且仅包含该产品的所有订单

时间:2014-04-06 04:51:08

标签: mysql

我有两张桌子

ORDERS
id
customer_name

ORDER_LINE_ITEMS
id
orders_id
product_id

如何查找仅包含单个商品的所有订单,特别是订购的product_id = 2?

1 个答案:

答案 0 :(得分:3)

可以简单地提取:

SELECT * FROM ORDERS WHERE ID IN
    (SELECT ORDERS_ID FROM ORDER_LINE_ITEMS 
         WHERE PRODUCT_ID = 2
         GROUP BY ORDERS_ID
         HAVING COUNT(ORDERS_ID) = 1
    )

如果您希望评论中只包含Product_id = 2且没有任何其他产品的订单,那么sql应该是这样的:

SELECT * FROM ORDERS WHERE ID IN
    (SELECT ORDERS_ID FROM ORDER_LINE_ITEMS 
         WHERE PRODUCT_ID = 2
         GROUP BY ORDERS_ID
         HAVING COUNT(ORDERS_ID) = 1
    )
and id not in
    (SELECT ORDERS_ID FROM ORDER_LINE_ITEMS 
         WHERE PRODUCT_ID <> 2
    )