使用 SQL 查询识别缺失的转化

Identify missing conversions with an SQL query

我需要找到一种方法来查找缺少的转化。

我有三个table。

Table 1: type, 是不同的 types.

id 姓名
1 类型A
2 类型B
3 C型

Table 2:section,这是不同的sections.

id 姓名
1 第 1 节
2 section2
3 第 3 节
4 第 4 节

Table 3: conversions,其中包含每个 sections.

从一个 type 到另一个的所有组合
id section_id type_convert_from type_convert_to
1 1 1 2
2 2 1 2
3 3 1 2
4 4 1 2
5 1 1 3
6 2 1 3
7 3 1 3
8 4 1 3
9 1 2 1
10 2 2 1
11 3 2 1
12 4 2 1

例如,上面的 table 中缺少一些,我如何使用 SQL 查询来识别它们?谢谢!

试试这个。 table type 与自身的交叉连接生成所有可能的类型 id 组合。我排除了交叉连接中的组合,其中 id_from = id_to(即您对从类型到自身的转换不感兴趣)

select * from conversions C 
    right join (
        select T1.id as id_from, T2.id as id_to 
        from type T1 cross join type T2
        where T1.id <> T2.id
        ) X on X.id_from = C.type_convert_from and X.id_to = C.type_convert_to
    where C.type_convert_from is null

如果要按部分检查缺少的类型转换,请通过添加 section table 来扩展交叉联接以包含 section.id,如下所示。它将列出每个部分中缺少的类型转换。

select X.section_id, X.id_from, X.id_to from conversions C 
right join (
    select S.id as section_id, T1.id as id_from, T2.id as id_to 
    from types T1 cross join types T2 cross join section S
     where T1.id <> T2.id
    ) X 
    on X.id_from = C.type_convert_from and X.id_to = C.type_convert_to
    and C.section_id = X.section_id
where C.type_convert_from is null