Z
Z
z4p2015-10-07 12:13:42
SQL
z4p, 2015-10-07 12:13:42

How to select data by conjunctive conditions on multiple links?

There are 3 tables (classic many2many):
Items ( id , name, price)
Orders ( id , time)
OrderItems ( order_id , item_id , count)
Disjunction selection (list of orders containing at least one of the elements) works like this:

SELECT * FROM Orders o
JOIN OrderItems i ON i.order_id = o.id
WHERE i.item_id IN (1, 2, 3)
GROUP BY o.id;

But how to select those orders from Orders that contain all the given elements (1, 2, 3)?
Without crooked type subqueries
(
SELECT COUNT(DISTINCT oi.item_id) 
FROM OrderItems oi 
WHERE oi.order = i.order AND oi.item_id IN (1, 2, 3) GROUP BY oi.order_id
) >= 3

Answer the question

In order to leave comments, you need to log in

1 answer(s)
T
Taxist410, 2015-10-07
@Taksist410

you can do this:
SELECT * FROM Orders o
JOIN OrderItems i1 ON i1.order_id = o.id AND i1.item_id =1
JOIN OrderItems i2 ON i2.order_id = o.id AND i2.item_id =2
JOIN OrderItems i3 ON i3.order_id = o.id AND i3.item_id =3
GROUP BY o.id;
but I like the "curve" subquery better.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question