我的也是属于你的,共享!
SQL:不要传任何列的条件参数,查询表中连续的某几条记录
如:表A,id列为主键
id name sex age
-------------------------
1 luoyi male 21
2 yaya female 20
3 lili female 22
4 wuyong male 25
.......................
这个表的记录还有很多,如果我想取第二、第三条记录,不为别的,我就想要这两条,这不仅在编程中会用到,而且在一些公司面试时也有类似考题(呵呵,我没有遇到过),在oracle和mssqlserver中SQL代码分别为:
一、Oracle
在oracle中不能用top关键字,而用rownum,有两种方法可以实现
1.(select * from A where rownum <= 4) minus (select * from A where rownum <= 1)
这样就得到了二、三两条记录了。minus 关键字的意思是求两个结果集的差集,在数学中有这个概念,比如说两个集合可以合并、公有、差集.
2. select * from (select * from A where rownum < 4) b where b.id not in(select id from A where rownum <2) 这句代码也可以实。主要运用了not in运算符
二、ms sql server
在server中没有minus,只能用类似于oracle的第二种方法
select * from (select top 3 * from A) as b where b.id not in(select top 1 id from A)
三、绘制出来的结果为:
id name sex age
--------------------------------
2 yaya female 20
3 lili female 22
四、欢迎大家七嘴八舌地说。
如:表A,id列为主键
id name sex age
-------------------------
1 luoyi male 21
2 yaya female 20
3 lili female 22
4 wuyong male 25
.......................
这个表的记录还有很多,如果我想取第二、第三条记录,不为别的,我就想要这两条,这不仅在编程中会用到,而且在一些公司面试时也有类似考题(呵呵,我没有遇到过),在oracle和mssqlserver中SQL代码分别为:
一、Oracle
在oracle中不能用top关键字,而用rownum,有两种方法可以实现
1.(select * from A where rownum <= 4) minus (select * from A where rownum <= 1)
这样就得到了二、三两条记录了。minus 关键字的意思是求两个结果集的差集,在数学中有这个概念,比如说两个集合可以合并、公有、差集.
2. select * from (select * from A where rownum < 4) b where b.id not in(select id from A where rownum <2) 这句代码也可以实。主要运用了not in运算符
二、ms sql server
在server中没有minus,只能用类似于oracle的第二种方法
select * from (select top 3 * from A) as b where b.id not in(select top 1 id from A)
三、绘制出来的结果为:
id name sex age
--------------------------------
2 yaya female 20
3 lili female 22
四、欢迎大家七嘴八舌地说。
...全文


非技术区
