我有两张桌子
ORDERS
id
customer_name
和
ORDER_LINE_ITEMS
id
orders_id
product_id
如何查找仅包含单个商品的所有订单,特别是订购的product_id = 2?
答案 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
)