日期:2014-05-19  浏览次数:20394 次

如何用 not exists 查询第三行记录
table:   stu

name       age

jac         20
tom         30
irs         25

要求不用临时表。

我要查出第三条,我使用
  select   top   1   *   from   stu   where   name   not   in   (select   top   2   name   from   stu)  

得到:   irs       25

据说,使用   not   exists   性能会好一些,我该如何修改呢??

谢谢了

------解决方案--------------------
select top 1 * from stu where not exists(select top 2 name from stu)
------解决方案--------------------
沒有太大的差距的說...
------解决方案--------------------
playwarcraft(时间就像乳沟,挤挤还是有的) ( ) 信誉:100 Blog 加为好友 2007-04-05 08:22:53 得分: 0


沒有太大的差距的說...


------------

他這種情況,可以用exists寫出來,得到他的結果?
------解决方案--------------------
to楼主:
请问‘第三条’,怎么个‘第三’?没有一个排序的规则么?
如果就按照你所给的那条来看,效率倒是没问题。
------解决方案--------------------
create table stu(name varchar(10),age int)
insert into stu
select 'jac ',20 union all
select 'tom ',30 union all
select 'irs ',25

--cost 42.51%
select top 1 * from stu where name not in (select top 2 name from stu)
/*
name age
---------- -----------
irs 25
*/

--cost 47.71%
select * from stu where not exists(select 1 from (select top 2 name from stu) t where name=stu.name)
/*
name age
---------- -----------
irs 25
*/

drop table stu

--------------------------------------------
以上2種對比not in 42.51% ,not exists 47.71%,前者還好點呢
------解决方案--------------------
--重來:)
-- 0.00%
create table stu(name varchar(10),age int)

--17.46%
insert into stu
select 'jac ',20 union all
select 'tom ',30 union all
select 'irs ',25 union all
select 'alen ',10 union all
select 'dav ',60

--38.77%
select top 1 * from stu where name not in (select top 2 name from stu)
/*
name age
---------- -----------
irs 25
*/

--43.78
set rowcount 1
select * from stu where not exists(select 1 from (select top 2 name from stu) t where name=stu.name)
set rowcount 0
/*
name age
---------- -----------
irs 25
*/


drop table stu
-------------------------------------------------------

------解决方案--------------------
有區別嗎?
------解决方案--------------------
据说,使用 not exists 性能会好一些,我该如何修改呢??

not in 与 not exists
不是所有的语句都会性能好

楼主以上用法用not in会好点:
没有排序规则的情况下,可以用下面方法:
declare @ta table (name varchar(10),age int)
insert into @ta
select 'jac ',20 union all
select 'tom ',30 union all
select 'irs ',25 union all
select 'alen ',10 union all
select 'dav ',60

select top 1 * from @ta where
binary_checksum(*) not in (select top 2 binary_checksum(*) from @ta)