简体   繁体   English

特定产品的mysql订单

[英]mysql orders with specific products

I have 3 tables orders, orders_products, and products. 我有3个表order,orders_products和products。 I have joined them to get products for each order.. 我已经加入他们的行列,以获取每个订单的产品。

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

Now I want to only get the orders that only have p.item_type = 1 or p.item_type = 2. (if an order has products of type 1, 2, and 3, don't show, only orders with product types 1 or 2) 现在,我只想获取仅具有p.item_type = 1或p.item_type = 2的订单。(如果订单的产品类型为1、2和3,则不显示,仅显示产品类型为1或2的订单。 2)

If you want only the orders, you can use group by and having . 如果只需要订单,则可以使用group byhaving The following gets orders with items 1 and 2 and none others: 以下内容获得包含商品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;

Note that the orders table is not needed. 请注意,不需要orders表。

You can use this having clause for 1 or 2 and no others: 您可以将此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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM