mysql - 使用 all() 或 exists() 返回一个表的 ID,其中其他表的所有值都与此 ID 一起存在

标签 mysql sql database dbms-output

我有以下数据的三个表

表 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/

相关文章:

sql - 如何用 SQL Server 中 nvarchar 字符串的单个换行符替换多个换行符

sql - 在哪里放置存储过程和交换数据库技术?

java - 在 Hibernate 4 中获取错误意外 token

php - 如何判断保存操作是插入还是更新?

php - Laravel 急切加载以最大程度地减少查询

mysql - 修改密码后无法登录mysql 5.7.9

sql - 如何使 SQL 符合 zIIP 处理的条件?

php - sql数据库中eloquent laravel中文支持

MySQL 数据库损坏

mysql - 一个表应该有多少列有限制吗?