用于检索关系表中缺少的组合的Mysql查询

用于检索关系表中缺少的组合的Mysql查询,mysql,database,combinations,relationship,Mysql,Database,Combinations,Relationship,我有四个表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

我有四个表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中选择表D中与IdB和IdC没有所有可能组合关系的所有ID?在上面的示例中,只有IdA=2具有所有组合,因此查询将返回表a中除id=2之外的所有id。

使用此查询可以获得缺少的组合:

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;
如果您只是希望表A中缺少的值不匹配,请使用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;