查詢表中連續的某幾條記錄

不要傳任何列的條件參數,查詢表中連續的某幾條記錄
如:表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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章