Table A: Table A_B: Table B:
id | a a_id | b_id id | b
------ ----------- ------
1 | w 1 | 1 1 | s
2 | x 1 | 2 2 | t
3 | y 2 | 4 3 | u
4 | z 4 | 4 4 | v
Now I'd like to have ALL entries from table A WHERE B.id = 1 AND B.id = 2.
At the moment I have to following code:
SELECT *
FROM A a
JOIN A_B ab ON a.id = ab.a_id
JOIN B b ON ab.b_id = b.id
And here I got stuck. WHERE b.id IN (...)
gives me all entries from Table A WHERE b.id = 1 OR b.id = 2
of course, and WHERE b.id = 1 AND b.id = 2
gives no results at all...
The only possible solution I found is using INTERSECT
:
SELECT *
FROM A a
JOIN A_B ab ON a.id = ab.a_id
JOIN B b ON ab.b_id = b.id
WHERE b.id = 1
INTERSECT
SELECT *
FROM A a
JOIN A_B ab ON a.id = ab.a_id
JOIN B b ON ab.b_id = b.id
WHERE b.id = 2
But I can have an infinite number of b.ids. So this query will become really slow...
Isn't there something like IN
which behaves like I want? And it should be implemented using Criteria Query:
Join<A, B> aB = root.join(A_.bs); // as this is a @ManyToMany relationship
...
But I'd also be happy with a pure SQL solution.
Tested on MySQL:
SQL Fiddle here.