資料庫高階查詢語句

2021-08-29 20:45:29 字數 1961 閱讀 3240

巢狀子查詢:

子查詢的優勢和特點

使用靈活,可以成為sql語句的多個部分

·子查詢作為查詢條件使用

·子查詢作為臨時表使用

降低sql語句的複雜度,提高sql語句的可讀性

作為臨時表使用

例:select stuname ,subject,score from

(select * from stuinfo where name='李四') s1,

(select * from stumarks where score > 80) s2,

where s1.stuid=s2.stuid

作為查詢條件使用

例:select * from stuinfo where stuid <

(select stuid from stuinfo where stuname = '王五')

作為列使用

例:select s.*,(select score stumarks where subject = 'html'

and s.stuid=stumarks.stuid) as '成績' from stuinfo s

使用in和not in完成子查詢

in和not in 通常在where子句中使用,在in和not in

後接的子查詢可以多個值出現大半年必須只能有一列

例:select * from stuinfo where stuid in (1,3)

not in和in的用法一樣只是意思相反

使用exists 和 not exists子查詢

·exists 和 not exists表示存在和不存在的意思

·在語句中會判斷exists 和 not exists後接的子句是否存在和是否不存在

·exists 和 not exists用法一樣,只是意思相反

例:select * from stuinfo where exists

(select * from stumarks where stumarks.stuid=stuinfo.stuid)

使用some、any、all進行子查詢

在sql查詢中some、any、all後必須跟子查詢

在sql查詢中,some和any的作用是一樣的,表示其中的任何一項

all則表示其中的所有的項

使用compute和compute by 進行彙總查詢

compute 進行彙總計算後查詢得到兩個結果集,第乙個是返回查詢語句前面的查詢明細

後乙個結果集返回彙總結果

需要對結果先進行分組然後進行彙總計算的時候可以使用compute by進行分組彙總查詢

排序函式

語法:排序函式 over([分組子句] 排序子句 [desc/asc])

row_number 函式生成的排序根據排序子句給出遞增連續的序號

rank 函式生成的排序根據排序子句給出遞增的序號,但是存在並列並且跳空

dense_rank函式生成的排序根據排序子句給出遞增連續的序號,但是存在並列不跳空

分組子句:partition by 分組列,分組列...

排序子句:order by 排序列,排序列...

例:select dense_rank() over(partition by subject order by score desc),

stuinfo.stuid,stuname,sbject from stuinfo,stumarks where

stuinfo.stuid=stumarks.stuid

公式表示式:

with g_name(stuid,stuname,score)as(

select s1.stuid,s1.stuname,s2.score

from stuinfo s1,stumarks s2

where s1.stuid=s2.stuid and subject='sql'

)select * from g_name

go

資料庫 高階查詢

巢狀查詢也叫子查詢,是把內層的查詢結果作為外層的查詢條件 語法格式 select 欄位名列表 from 表名 where 欄位名 運算子 select 欄位名 from 表名 where 條件 注意 外層的where的條件必須和內層的select查詢的欄位名一樣,個數也一樣 如 把攻擊值小於平均攻擊...

資料庫查詢語句

表示要查詢所有列 select from t student 查詢所有人的姓名資訊 select stu name from t student 查詢張乾的手機號和位址 select stu mobile,stu address from t student where stu name 張乾 查詢...

資料庫 查詢語句

隱式連線 select coursename,teachername from courses inner join teachers on courses.teacherid teahcer.teacherid 等價於顯式連線 select coursename,teachername from ...