[英]MYSQL - Select values in table A where all the corresponding values in table B have a specific values
I have two tables, orders
and ordered_products
. 我有两个表,
orders
和ordered_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 |...
I need two queries, the first to select all orders that have at least one product of type 1, the second to select all orders that have ALL products of type 1. 我需要两个查询,第一个查询选择所有类型至少为 1的产品,第二个查询选择所有类型均为1的产品。
For the first one i have solved with the following query: 对于第一个,我使用以下查询解决了:
select distinct orders_id from ORDERS o left join ORDERED_PRODUCTS op on (o.orders_id=op.orders_id) where op.product_type = '1'
But I can't find a solution for the second query. 但是我找不到第二个查询的解决方案。
Solution found! 找到解决方案! I used:
我用了:
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')
Thank you for the help 感谢您的帮助
Not tested, but this should work : 未经测试,但这应该工作:
select orders_id
from orders
where
(
select count(distinct product)
from ordered_products
where ordered_products.orders_id = orders.orders_id
and ordered_products.product_type = 1
)
=
(
select count(distinct product)
from ordered_products
where ordered_products.product_type = 1
);
What it does : 它能做什么 :
It's far from optimized and there probably are better methods, but it does the work and it's easily understandable. 它远未优化,可能还有更好的方法,但它确实有效,而且易于理解。
PS : If you have the choice of the database structure, I'd go for having a different table for products themselves. PS:如果您可以选择数据库结构,那么我会为产品本身使用不同的表。 Fits better in UML specifications, less redundancy, better indexing.
更适合UML规范,更少的冗余,更好的索引编制。
First query: 第一个查询:
SELECT *
FROM Orders
WHERE Exists (select null
from ordered_products
where
orders.orders_id = ordered_products.orders_id
and product_type=1)
And the second one: 第二个:
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(*))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.