返回表的id,其中使用all()或exists()以此id存在其他表的所有值

rcb*_*_sp 6 mysql sql database dbms-output

我有三个包含以下数据的表格

表3 :

Table1_id        Table2_id
1                1
1                2
1                3
2                1
2                3
3                2
Run Code Online (Sandbox Code Playgroud)

表2:

Table2_id        Name
1                A
2                B
3                C
Run Code Online (Sandbox Code Playgroud)

表格1 :

Table1_id        Name
1                P
2                Q
3                R
Run Code Online (Sandbox Code Playgroud)

我有一个问题,我需要返回所有table1_id,其中有表3中所有Table2_ids的条目.
即.我想要我的输出

Table1_id
1
Run Code Online (Sandbox Code Playgroud)

我找到了一个使用count()的解决方案.但有没有办法使用all()或exists()来解决查询?

Pau*_*gel 3

在带有 a 的子选择中使用NOT INwith 排除LEFT JOINCROSS 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
)
Run Code Online (Sandbox Code Playgroud)

VS使用COUNT()

select table1_id 
from table3 
group by table1_id 
having count(1) = (select count(1) from table2)
Run Code Online (Sandbox Code Playgroud)

解释:

CROSS JOIN

    select t1.Table1_id
    from table1 t1
    cross join table2 t2
Run Code Online (Sandbox Code Playgroud)

表示table3如果 中的每个项目都与table1中的每个项目相关,将会是什么样子table2

(自然的)左连接table3将向我们展示哪些关系真正存在。通过where t3.Table1_id is null(排除LEFT JOIN)过滤,我们得到了缺失的关系。使用该NOT IN子句的结果,我们仅获得与表 2 没有缺失关系的表 1 项目。