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

如何找出表2有而表1没有的记录
各位朋友,表1和表2如下:
语句:select * from 表2 where no not in(select no from 表1) 可以找出表2有而表1没有的记录,但是,想加多一个条件,找出来的结果,最大的数值不能超过表1最大的NO-7,最终想实现的结果如下:

最后想要的结果:
NO
4
5
6

错误的结果:
NO
4
5
6
8
9
10


表1 
NO 
1
2
3
7


表2
NO
1
2
3
4
5
6
7
8
9
10

请各位朋友赐教,谢谢!!!


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

SQL code
select [no] from 表2 where [no]<=(select max([no]) as [no] from 表1) and  [no] not in(select [no] from 表1)

------解决方案--------------------
select t1.* from t1 left join t2 on t1.no=t2.no where t2.no is null and t1.no!>(select max(no-1) from t1 )
------解决方案--------------------
SQL code


create table #1(id int)
insert into #1 select 1
insert into #1 select 2
insert into #1 select 3
insert into #1 select 7

create table #2(id int)
insert into #2 select 1 
insert into #2 select 2
insert into #2 select 3
insert into #2 select 4
insert into #2 select 5
insert into #2 select 6
insert into #2 select 7
insert into #2 select 8
insert into #2 select 9
insert into #2 select 10

select * from #2 a
where not exists(select 1 from #1 b where a.id=b.id ) and a.id<=(select max(id) from #1) 
/*
--
id
4
5
*/

------解决方案--------------------
select * from #2 a
where not exists(select 1 from #1 b where a.id=b.id ) and a.id<=(select max(id) from #1)