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

查询的一个怪问题
这是我的一个表   checkt     ,我要查询第4条和第5条数据
create   table   checkt(id   int,dt   varchar(10)   )  
insert   into   checkt     values(1, 'a ')
insert   into   checkt     values(2, 'b ')
insert   into   checkt     values(3, 'c ')
insert   into   checkt     values(4, 'd ')
insert   into   checkt     values(5, 'f ')
insert   into   checkt     values(6, 'g ')
go

有3种方案...:
1> select   top   5   *   from   checkt   where   in   not   in   (select   top   3     id   from     check)
----结果是第6条和第5条...不理解为什么
2> select   top   2   *   from   (select   top   5   *   from   checkt)     aa   order   by   id   desc
----结果也是不是我要的,也不理解为什么不是我要的结果,理论上应该是我要的结果.但返回值不是我要饿
3> select   *   from   chectk
where   id= '4 '     or   id= '5 '   正确  

现在想请教大人解释第一种和第2种为什么不对

------解决方案--------------------
1. top 5 查的是5條,而不是2條
改為
select top 2 * from checkt where id not in (select top 3 id from checkt order by id)
------解决方案--------------------
先说说认为第1种和第2种对的理由
------解决方案--------------------
2.
select top 2 * from (select top 5 * from checkt order by id) aa order by id desc
------解决方案--------------------
select top 2 * from checkt
where id not in (select top 3 id from check order by id)
order by id

------解决方案--------------------
create table checkt(id int,dt varchar(10) )
insert into checkt values(1, 'a ')
insert into checkt values(2, 'b ')
insert into checkt values(3, 'c ')
insert into checkt values(4, 'd ')
insert into checkt values(5, 'f ')
insert into checkt values(6, 'g ')
go

select * from
(select top 5 * from checkt) t where id not in
(select top 3 id from checkt)

drop table checkt

/*
id dt
----------- ----------
4 d
5 f
(所影响的行数为 2 行)
*/
------解决方案--------------------
(select top 3 id from check)这个里面都需要排序吧。
------解决方案--------------------
1> select top 5 * from checkt where id not in (select top 3 id from check)
----结果是第6条和第5条第4条 不理解为什么

查询出来的是除开前3后的前5条记录

2> select top 2 * from (select top 5 * from checkt) aa order by id desc
----结果也是不是我要的,也不理解为什么不是我要的结果,理论上应该是我要的结果.但返回值不是我要饿

sql里把 select top 2 * from (select top 5 * from checkt) aa order by id desc 看成了
select top 2 * from (select top 5 * from checkt order by id desc) aa

3> select * from chectk
where id= '4 ' or id= '5 ' 正确

可以写成
select top 2 * from checkt where id not in (select top 3 id from checkt)