进来项目中用到很多sql的语句,其中有个需求:
有两个表table1、table2,需要找出table1中存在,而table2中不存在的数据。要求不能使用NOT IN语句。
举例:两表的数据如下:
现在要从table1中选出记录,记录的f3字段不在table2中出现。
一、简单的使用NOT IN
select f1,f2,f3 from table1 where f3 not in(select f from table2);
得到结果:
二、不用NOT IN
select res.f1,res.f2 from (select f1,f2,table2.f as tmp_colum from table1 left outer join table2 on table1.f3=table2.f) as res where res.tmp_colum is null;
使用left outer join来完成所需任务,其中的语句
select f1,f2,table2.f as tmp_colum from table1 left outer join table2 on table1.f3=table2.f
结果为:
结果不言而喻,在在此基础上进行的筛选,选出两者交际为空的,就是table1不在table2 中的结果集。