日期:2014-05-18  浏览次数:20489 次

关于SQL查询
在SQL里有两个表,两个表都有相同的字段,(如:姓名,年龄,性别),通过怎样的查询得到表1中的记录,而这些记录在表2中不存在(即在表1中查找表2中不存在的记录)

------解决方案--------------------

根据你的主键来进行判断

select a.* from 表1 a where not exists(select 1 from 表2 where a.主键=主键)
------解决方案--------------------
select * from tb1 where 主键 not in (select 主键 from tb2)
------解决方案--------------------
只查主键

select * from 表1 where 主键 not in (select 主键 from 表2)

姓名,年龄,性别
select * from 表1 where cast(姓名 as varchar) + cast(年龄 as varchar) + cast(性别 as varchar) not in (select cast(姓名 as varchar) + cast(年龄 as varchar) + cast(性别 as varchar) from 表2)

如果全部字段都相同
用checksum


------解决方案--------------------
select *
from 表1 a
where not exists (select * from 表2 b where b.主键=a.主键)
------解决方案--------------------
select * from tb1 where 主键 not in (select 主键 from tb2)
------解决方案--------------------
select * from 表1 a where not exists(select 1 from 表2 b where a.姓名=b.姓名 and
a.年龄=b.年龄 and a.性别=b.性别)