我从2012年11月开始有一张包含14,028行的表格。从2013年3月开始,我还有一张包含13,959行的表格。我使用一个简单的NOT IN()
子句来查看谁离开了:
select * from nov_2012 where id not in(select id from mar_2013)
这返回了396行,我从未想过它,直到我去分析谁离开了。当我为丢失的成员提取所有ID并将它们放入临时表(##lost
)时,其中32个实际上仍然在mar_2013
表中。当我使用以下内容搜索他们的ID时,我可以将它们拉出来:
select * from mar_2013 where id in(select id from ##lost)
我无法弄清楚发生了什么。我会提到我创建的id
字段是IDENTITY
列。这会对使用NOT IN
的匹配产生任何影响吗?有没有更好的方法来检查表之间缺少的行?我也尝试过:
select a.* from nov_2012 a left join mar_2013 b on b.id = a.id where b.id is NULL
并收到了同样的结果。
这是我创建身份字段的方式;
create table id_lookup( dateofcusttable date ,sin int ,sex varchar(12) ,scid int identity(777000,1))
insert into id_lookup (sin, sex) select distinct sin, sex from [Client Raw].dbo.cust20130331 where sin <> 0 order by sin, sex
这就是我将scid添加到行军表中的方式:
select scid, rowno as custrowno
into scid_20130331
from [Client Raw].dbo.cust20130331 cust
left join id_lookup scid
on scid.sin = cust.sin
and scid.sex = cust.sex
update scid_20130331
set scid = custrowno where scid is NULL --for members who don't have more than one id or sin information is not available
drop table Account_Part2_Current
select a.*, scid
into Account_Part2_Current
from Account_Part1_Current a
left join scid_20130331 b
on b.custrowno = a.rowno_custdmd_cust
然后我按照scid
对所有信息进行分组答案 0 :(得分:9)
我更喜欢这种形式(和here's why):
SELECT a.id --, other columns
FROM dbo.nov_2012 AS a
WHERE NOT EXISTS (SELECT 1 FROM dbo.mar_2013 WHERE id = a.id);
然而,这仍然应该与您尝试的结果相同,所以我怀疑您没有告诉我们数据模型的某些内容 - 例如,mar_2013.id
是否可以为空?
答案 1 :(得分:0)
这在逻辑上等同于不存在并且比不存在更快。
where yourfield in
(select afield
from somewhere
minus
select
thesamefield
where you want to exclude the record
)
根据Aaron的回答,它可能没有使用不存在的那么快,所以你只应该使用它,如果不存在则不能提供你想要的结果。