有两张测试表,数据如下:
表1:
表2:
查询语句:
select * from t_n01 a where sfz not in(select b.sfz from t_n02 b where a.xm=b.xm and a.sfz=b.sfz);
查出来的结果如下:
请教各路大神,为什么'李四','123'这条记录会查出来?
我本意是查询:只要表2中数据出现在表1中,查出对应的sfz字段,然后在表1中查询不包含这些sfz的数据。怎么修改上面的语句才能实现这种结果?用not exists能否实现?
因为select * from t_n01 a where sfz not in(select b.sfz from t_n02 b where a.xm=b.xm and a.sfz=b.sfz);中()里的查询时and,必须两个字段都相等
select * from t_n01 a where not exists (select 1 from t_n02 b where a.xm=b.xm and a.sfz=b.sfz);
你改成下面的就可以达到你要的效果了
select * from t_no1 where sfz not in(select b.sfz from t_n01 a, t_n02 b where a.xm=b.xm and a.sfz=b.sfz);
如果你的本意是查询表一中与表二不同的数据,那么你原先写的就是对的。
能力有限,只能做到这了