我有以下数据的三个表
表 3:
Table1_id Table2_id
1 1
1 2
1 3
2 1
2 3
3 2
表 2:
Table2_id Name
1 A
2 B
3 C
表 1:
Table1_id Name
1 P
2 Q
3 R
我遇到了一个问题,我需要返回所有 table1_id,其中包含表 3 中所有 Table2_id 的条目。
即。我希望我的输出是
Table1_id
1
我找到了一个使用 count() 的解决方案。 但是有没有办法使用 all() 或 exists() 来解决查询呢?
最佳答案
在带有CROSS JOIN
的子选择中使用NOT IN
并排除LEFT JOIN
select *
from table1
where Table1_id not in (
select t1.Table1_id
from table1 t1
cross join table2 t2
left join table3 t3 using (Table1_id, Table2_id)
where t3.Table1_id is null
)
VS 使用 COUNT()
select table1_id
from table3
group by table1_id
having count(1) = (select count(1) from table2)
解释:
交叉连接
select t1.Table1_id
from table1 t1
cross join table2 t2
表示 table3
的样子,如果 table1
中的每个项目都与 table2
中的每个项目相关。
table3
的(自然)左连接将向我们展示哪些关系确实存在。通过 where t3.Table1_id is null
(不包括 LEFT JOIN
)过滤,我们得到缺失的关系。将该结果用于 NOT IN
子句,我们只得到与 table2 没有缺失关系的 table1 项目。
关于mysql - 使用 all() 或 exists() 返回一个表的 ID,其中其他表的所有值都与此 ID 一起存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36258978/