I have two tables, orders and 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.
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 :
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. Fits better in UML specifications, less redundancy, better indexing.