具有特定产品的mysql订单

时间:2017-02-09 03:03:36

标签: mysql sql database

我有3个表订单,orders_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)

1 个答案:

答案 0 :(得分:0)

如果您只想要订单,可以使用group byhaving。以下是订单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;