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

输入问题?关于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 test1 as t1 where not exists(select * from test2 where t.id=test2.id)