SQL學習筆記-巢狀查詢

來源:互聯網
上載者:User
巢狀查詢
定義:
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 ' )
最後這一個不是很好理解呀!等用多了就好了。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.