我有两张桌子Core和BKP。表BKP包含带有重复项的数据。但是核心包含相同的数据,没有重复。
两个表的主键是4个字段(1,2,3,4)的组合。
但是在运行一些脚本后,Core表中的一些记录错过了。
如何从Core表中找出错过的记录,(错过的记录肯定存在于BKP中但有重复记录)。
答案 0 :(得分:0)
使用NOT EXISTS:
Select b.PK1,b.PK2,b.PK3,b.PK4 --Primary key from BKP missed in CORE
from
(--select all PK existing in BKP
select
distinct
b.PK1,b.PK2,b.PK3,b.PK4 --Primary key from BKP
from BKP b) b
where not exists(select 1 from CORE c
where c.PK1=b.PK1
and c.PK2=b.PK2
and c.PK3=b.PK3
and c.PK4=b.PK4
)
使用LEFT JOIN:
Select b.PK1,b.PK2,b.PK3,b.PK4 --Primary key from BKP missed in CORE
from
(--select all PK existing in BKP
select
distinct
b.PK1,b.PK2,b.PK3,b.PK4 --Primary key from BKP
from BKP b
) b
left join
(select c.PK1,c.PK2,c.PK3,c.PK4 --Primary key from CORE
from CORE c
) c
on c.PK1=b.PK1
and c.PK2=b.PK2
and c.PK3=b.PK3
and c.PK4=b.PK4
where c.PK1 is null --absent in CORE