[英]mysql orders with specific products
我有3個表order,orders_products和products。 我已經加入他們的行列,以獲取每個訂單的產品。
SELECT o.orders_id, p.products_id, p.item_type
from orders o
join orders_products op on o.orders_id = op.orders_id
join products p on op.products_id = p.products_id
現在,我只想獲取僅具有p.item_type = 1或p.item_type = 2的訂單。(如果訂單的產品類型為1、2和3,則不顯示,僅顯示產品類型為1或2的訂單。 2)
如果只需要訂單,則可以使用group by
並having
。 以下內容獲得包含商品1和2的訂單:
select op.orders_id
from orders_products op join
products p
on op.products_id = p.products_id
group by op.orders_id
having sum(p.item_type = 1) > 0 and
sum(p.item_type = 2) > 0 and
sum(p.item_type not in (1, 2)) = 0;
請注意,不需要orders
表。
您可以將此having
子句用於1或2,不能用於其他子句:
having sum(p.item_type in (1, 2) > 0 and
sum(p.item_type not in (1, 2)) = 0;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.