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