Mysql 查询检索关系表中缺失的组合

标签 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 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 byhaving:

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/

相关文章:

php - 为什么当我尝试登录时,数据库中的登录详细信息仍然被脚本声明为无效?

mysql - 重度平均MYSQL

需要优化的 MySQL 查询/表

mysql - 如何以良好的方式将多个 django 表单保存到数据库中?提高绩效

java - 对数据库或数组进行排序

.net - 构建 List<string> 的所有可能的排序组合

mysql - 如何在带有 SUM 的多重连接查询中包含 DISTINCT

php - AJAX——数据库连接

c++ - vector 值的不同组合

algorithm - 找到以一定精度求和到给定数组的 K 个数组