最近在學sql,遇到了這麼一道題:
寫出一條sql
語句:取出表a中第
31到第
40記錄(
sqlserver,
以自動增長的
id作為主鍵
,注意:
id可能不是連續的。
把所能想到的實現方法都做了一遍:
1.用集合查詢
selecttop40
*from
t_test
except
select
top30
*from t_test
2.用not in 謂詞
selecttop10
*from t_test where
idnot
in(select
top30 id from t_test)
3.用all謂詞
selecttop10
*from t_test where
id>all(select
top30 id from t_test)
4.用max聚集函式
selecttop10
*from t_test where
id>(select
max(id) from (select
top30 id from t_test) as a)
這裡有些問題,因為 帶有 top子句 的子查詢 沒有 order by 子句 排序的話,max(id)作用的就是t_test基本表,而不僅僅是a這個結果集,所以max(id)會取到整個t_test表的最大值,從而整個查詢沒有結果。
改正:
selecttop10
*from t_test where
id>(select
max(id) from (select
top30 id from t_test order
by id) as a)
5.用開窗函式
select id,name from (select*, row_number() over(order
by id) as num from t_test) as
swhere s.num between
31and
40
Oracle入門SQL練習(一)
以下內容以scott使用者下oracle自帶例項orcl庫中四張表進行查詢,此部分為簡單查詢,作為練習筆記進行記錄 1 查詢乙個使用者下所有的表 select from tab 2 查詢一張表的結構 命令列 desc 表名稱 desc dept 簡單查詢語法結構 select distinct 列名...
SQL基礎總結(一)
什麼是 sql?sql 指結構化查詢語言。sql 使我們有能力訪問資料庫,是一種 ansi 的標準計算機語言 sql 能做什麼?sql 面向資料庫執行查詢,可從資料庫取回資料 查 可在資料庫中插入新的記錄 增 可更新資料庫中的資料 改 可從資料庫刪除記錄 刪 可建立新資料庫,可在資料庫中建立新錶,可...
資料庫sql 練習一
最近接觸了一到資料庫sql的題目,在這裡記錄一下,方便以後檢視,也歡迎各位小夥伴一起學習,如果不對,還請指出,萬分感激。題目 一。根據下面四個表,寫出sql 我直接在資料庫中新建了這幾張表,建庫指令碼語句如下 create table pe student id int 9 grade id int...