我有四个表(A、B、C 和 D)。表“D”具有与其他三个表的 FK 关系。查询如何从表“A”中检索与表“D”中的 B 和 C 表记录 ID 没有完整组合的所有 ID?示例:
表A
id Value
1 Orange
2 Apple
3 Lemon
4 Strawberry
6 Grape
表B
id value
1 Juice
2 Ice cream
表C
id Value
1 $10
2 $20
表D
id IdA IdB IdC Value
1 2 2 1 Desc 1
2 2 1 1 Desc 2
3 2 2 2 Desc 3
4 2 1 2 Desc 3
5 1 1 1 Desc 4
6 3 2 1 Desc 5
如何从表 A 中选择所有 id,但表 D 中不具有 IdB 和 IdC 的所有可能组合(关系)?在上面的示例中,只有 IdA = 2 具有所有组合,因此查询将返回表 A 中的所有 id,除了 id = 2。
最佳答案
您可以使用此查询获取缺少的组合:
select a.*, b.*, c.*
from tablea a cross join
tableb b cross join
tablec c left outer join
tabled d
on d.ida = a.id and d.idb = b.id and d.idc = b.id
where d.ida is null;
如果您只想从 tablea
中查找没有匹配项的缺失值,请使用 group by
和 having
:
select a.*
from tablea a cross join
tableb b cross join
tablec c left outer join
tabled d
on d.ida = a.id and d.idb = b.id and d.idc = b.id
where d.ida is null
group by a.id
having sum(d.ida is null) > 0;
关于Mysql 查询检索关系表中缺失的组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24563685/