定義:
1 .指在一個(gè)外層查詢(xún)中包含有另一個(gè)內(nèi)層查詢(xún)。其中外層查詢(xún)稱(chēng)為主查詢(xún),內(nèi)層查詢(xún)稱(chēng)為子查詢(xún)。
2 .SQL允許多層嵌套,由內(nèi)而外地進(jìn)行分析,子查詢(xún)的結(jié)果作為主查詢(xún)的查詢(xún)條件
3 .子查詢(xún)中一般不使用order by子句,只能對(duì)最終查詢(xún)結(jié)果進(jìn)行排序
子查詢(xún)(sub query)
where 表達(dá)式 [ not ] in (子查詢(xún))
where 表達(dá)式 比較運(yùn)算符 [ any|all ] 子查詢(xún)
where [ not ] exists (子查詢(xún))
1 .子查詢(xún)-單值比較
返回單值子查詢(xún),只返回一行一列
主查詢(xún)與單值子查詢(xún)之間用比較運(yùn)算符進(jìn)行連接:
運(yùn)算符: > , >= , < , <= , = , <>
例:找出與太行同齡的同事
select * from company
where age = ( select age from company
where name = taihang)
2 .子查詢(xún)- in
例:查詢(xún)選修了‘ 001 ’課程的學(xué)生學(xué)號(hào),姓名。
select id,name
from student
where id in ( select id
from taihang
where id = ‘ 001 ‘ )
3 .子查詢(xún)-多值比較all
多行一列
1 .父查詢(xún)與多值子查詢(xún)之間的比較需用all來(lái)連接
2 .標(biāo)量值S比子查詢(xún)返回集R中的每個(gè)都大時(shí),s >all ,r為true
3 .all表示所有
4 . >all ,
例:找出年齡最小的學(xué)生
select * from student
where age
4 .子查詢(xún)-多值比較some /any
1 .父查詢(xún)與多值子查詢(xún)之間的比較需用some / any來(lái)連接
2 .標(biāo)量值S比子查詢(xún)返回集r中的某一個(gè)都大時(shí),s > some時(shí)r為true 或s > any時(shí)r為true
3 .some表示部分
4 . >some , >=some , =some ,
例:找出不是最小年齡的學(xué)生
select * from student
where age > some ( select age from student)
5 .子查詢(xún)-存在判斷exists
1 . exists 子查詢(xún)用來(lái)判斷該子查詢(xún)是否返回元組
2 .當(dāng)子查詢(xún)的結(jié)果集非空時(shí),exists為true
3 .當(dāng)子查詢(xún)的結(jié)果集為空時(shí),exists為false
4 .不關(guān)心子查詢(xún)的具體內(nèi)容,因此用select *
例:列出先修了C01課程的學(xué)習(xí)的學(xué)號(hào),姓名
select son,sname
from strdent
where exists ( select * from sc
where sc.sno = stusent.sno and
cno = ‘ C01 ‘ )
最后這一個(gè)不是很好理解呀!等用多了就好了。="some">