我有一个具有多对多关系的简单 SQL 关系模型。这是组成表
___________________________ | object1_id | object2_id | |---------------------------------------|
我想知道object1
一组object2
. 我的基本感觉是做这样的请求
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>
如果我在集合中有 N 个 object2,我会做 NINTERSECT
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>
但是,它看起来并不是很优化。你能帮助我吗 ?我不是真正的 SQL 专家。我想我可以使用 JOIN 来做到这一点。
样本
___________________________ | object1_id | object2_id | |---------------------------------------| | 10 | 1 | | 11 | 1 | | 10 | 2 | | 12 | 2 | | 10 | 3 | | 11 | 3 | | 13 | 3 |
例子
- {
object2_id
设置 } => { 预期object1_id
} - { 1, 2 } => { 10 }
- { 1, 3 } => { 10, 11 }
- { 1, 2, 3 } => { 10 }