Find missing records from sequence

放肆的年华 提交于 2021-02-10 15:54:59

问题


I need to find the missing records in a table. Table 1:

ID|Num
X|1
X|2
X|3
X|4
Y|1
Y|3
Y|5

Table 2:

Num
1
2
3
4
5

I need to return:

ID|Num

X|5

Y|2

Y|4

I've found other solutions that would give me 5,2,4 but I need the ID associated with the missing record as well.


回答1:


If you want the missing numbers, use a cross join to generate all numbers and then filter out the ones that exist:

select i.id, t2.num
from (select distinct id from t1) i cross join
     table2 t2 left join
     t1
     on t1.id = i.id and t1.num = t2.num
where t1.id is null;


来源:https://stackoverflow.com/questions/57664065/find-missing-records-from-sequence

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!