MYSQL - 选择表A中的值,其中表B中的所有相应值都具有特定值

时间:2012-11-13 10:29:59

标签: mysql join

我有两个表,ordersordered_products

ORDERS
|ORDERS_ID|CUSTOMER NAME|...
|1        |PIPPO        |...
|2        |PLUTO        |...

ORDERED PRODUCTS
|ORDERED_ID|ORDERS_ID|PRODUCT  |PRODUCT_TYPE|...
|1         |1        |ProdottoA| 1          |...
|2         |1        |ProdottoB| 2          |...
|3         |1        |ProdottoC| 1          |...
|4         |2        |ProdottoD| 2          |...

我需要两个查询,第一个选择至少一个类型1的产品的所有订单,第二个选择所有类型为1的所有产品的订单。

对于我用以下查询解决的第一个:

select distinct orders_id from ORDERS o left join ORDERED_PRODUCTS op on (o.orders_id=op.orders_id) where op.product_type = '1'

但我无法找到第二个查询的解决方案。


找到解决方案!我用过:

select distinct orders_id from ORDERS o left join ORDERED_PRODUCTS op on (o.orders_id=op.orders_id) 
where
(select count(ordered_id) from ordered_products op where op.orders_id = o.orders_id)
=
(select count(ordered_id) from ordered_products op where op.orders_id = o.orders_id and op.orders_products_categorizzazione='1')

感谢您的帮助

1 个答案:

答案 0 :(得分:0)

首先查询:

SELECT *
FROM Orders
WHERE Exists (select null
              from ordered_products
              where
                orders.orders_id = ordered_products.orders_id
                and product_type=1)

第二个:

SELECT *
FROM Orders
WHERE
  Orders_id in (select orders_id
                from ordered_products
                where ordered_products.orders_id = orders.orders_id
                group by orders_id
                having sum(if(product_type=1,1,0))=count(*))