I have a simple SQL relational model with a many to many relation. Here is the composition table
___________________________ | object1_id | object2_id | |---------------------------|
I would like to know all the object1
that are common to a set of object2
. My basic feeling is to do a request like this
SELECT c.object1_id FROM composition c WHERE c.object2_id = <given_id_1>
INTERSECT
SELECT c.object1_id FROM composition c WHERE c.object2_id = <given_id_2>
And if I have N object2 in the set, I'll do N INTERSECT
SELECT c.object1_id FROM composition c WHERE c.object2_id = <given_id_1>
INTERSECT
SELECT c.object1_id FROM composition c WHERE c.object2_id = <given_id_2>
...
INTERSECT
SELECT c.object1_id FROM composition c WHERE c.object2_id = <given_id_N>
However, it doesn't look very optimized. Can you help me ? I am not really a SQL expert. I think I could use a JOIN to do that.
Sample
___________________________ | object1_id | object2_id | |---------------------------| | 10 | 1 | | 11 | 1 | | 10 | 2 | | 12 | 2 | | 10 | 3 | | 11 | 3 | | 13 | 3 |
Example
- {
object2_id
set } => { expectedobject1_id
} - { 1, 2 } => { 10 }
- { 1, 3 } => { 10, 11 }
- { 1, 2, 3 } => { 10 }