I need to find a way to find what conversions are missing.
I have three tables.
Table 1
: type
, which are the different types
.
id | name |
---|---|
1 | typeA |
2 | typeB |
3 | typeC |
Table 2
: section
, which are the different sections
.
id | name |
---|---|
1 | section1 |
2 | section2 |
3 | section3 |
4 | section4 |
Table 3
: conversions
, which contains all the combinations to go from one type
to another for each of the sections
.
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 |
For example some are missing from the table above, how can I identify them with a SQL query? Thanks!
Try this. The cross join of table type
with itself generates all possible combinations of type id's. I've excluded combinations in the cross join where id_from
= id_to
(ie you're not interested in conversions from a type to itself)
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
If you want to check missing type conversions by section, extend the cross join by adding the section
table to include section.id
as follows. It will list missing type conversions within each section.
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.