我有两个具有以下结构的表:
1。 City_Details: 该表包含每个城市的所有适用表格和列。
Country_Name City_Name Table_Name Column_Name USA New York T1 T1C1 USA New York T1 T1C2 USA New York T1 T1C3 USA New York T2 T2C1 USA Los Angeles T2 T2C1 USA Los Angeles T2 T2C2 USA Los Angeles T2 T2C3 England London T1 T1C1 England London T3 T3C1 England London T3 T3C2
2。 Max_Column_Details :此表包含有关每个城市可以存在的所有表的信息以及每个表可以拥有的最大列数。
Table_Name Column_Name T1 T1C1 T1 T1C2 T1 T1C3 T1 T1C4 T2 T2C1 T2 T2C2 T2 T2C3 T2 T2C4 T2 T2C5 T2 T2C6 T3 T3C1 T3 T3C2 T3 T3C3 T4 T4C1 T4 T4C2
我想编写一个SQL查询,只返回每个城市中PRESENT表的缺失列。例如,纽约的T1有3列T1C1,T1C2,T1C3。 T1最多可以有四列,即T1C1,T1C2,T1C3,T1C4。因此,纽约表T1的缺失列是T1C4。同样,需要其他城市的其他表的缺失列。所以结果应该如下:
Country_Code City_Code Table_Name Column_Name USA New York T1 T1C4 USA New York T2 T2C2 USA New York T2 T2C3 USA New York T2 T2C4 USA New York T2 T2C5 USA New York T2 T2C6 USA Los Angeles T2 T2C4 USA Los Angeles T2 T2C5 USA Los Angeles T2 T2C6 England London T1 T1C2 England London T1 T1C3 England London T1 T1C4 England London T3 T3C3
我尝试了一些使用MINUS,EXCEPT,EXIST和NOT EXIST的查询,但我仍然无法获得所需的结果。我对SQL不太熟练。请帮忙。
答案 0 :(得分:1)
with ct as (select distinct Country_Name, City_Name, Table_Name
from City_Details)
select ct.Country_Name, ct.City_Name, m.Column_name
from ct, Max_Column_Details m
where ct.Table_Name = m.Table_Name
and not exists ( select 1 from City_Details
where Country_Name = ct.Country_Name
and City_Name = ct.City_Name
and Table_Name = ct.Table_Name
and Column_Name = m.Column_Name )
order by 1, 2, 3;
应该做的伎俩