目錄
普通子查詢:
返回乙個值的普通子查詢
返回一組值的普通子查詢——使用any
返回一組值的普通子查詢——使用all
相關子查詢:
子查詢分為普通子查詢和相關子查詢。他們執行順序是不一樣的。
執行順序:先執行子查詢,子查詢返回結果之後,再執行父查詢。
[例]查詢與『劉偉』老師職稱相同的教師號、姓名。
select tno,tn from t where prof =(select prof from t where tn='劉偉')
[例]查詢講授課程號為c5的教師姓名
select tn from t where (tno=any(select tno from tc where cno='c5'))
或者
select tn from t where (tno in (select tno from tc where cno='c5'))
或者
select tn from t,tc where t.tno=tc.tno and tc.cno='c5' /*多關係表的連線查詢*/
*教師授課表中找到課程號為c5的教師號tn,然後在教師表中找到教師號對應的教師姓名。(教師表有教師號和教師姓名,教師授課表有教師號和講授課程號)
[例]查詢其他系中比計算機系某一教師工資高的教師的姓名和工資。
select tn,sal from t where (sal>any(select sal from t where dept='計算機')) and (dept<>'計算機')
或者
select tn,sal from t where sal>(select min(sal) from t where dept='計算機') and dept<>'計算機' /*返回最低工資*/
[例]查詢其他系中比計算機系所有教師工資都高的教師姓名和工資。
select tn,sal from t where ( sal> all (select sal from t where dept='計算機')) and (dept<>'計算機')
或者
select tn,sal from t where sal>(select max(sal) from t where dept='計算機') and dept<>'計算機' /*返回最高工資*/
執行順序:
選取父查詢表中的第一行記錄,內部的子查詢利用此行中相關的屬性值進行查詢;
父查詢根據子查詢返回的結果判斷此行是否滿足查詢條件。如果滿足條件,則把該行放入父查詢的查詢結果集合中。
重複執行這一過程,直到處理完父查詢表中的每一行資料。
使用exists
帶有exists的子查詢不返回任何實際資料,他只能得到邏輯值「真」或「假」。
當子查詢的查詢結果為非空時,外層的where子句返回真值,否則返回假值。not exists與此相反。
[例]用含有exists的語句查詢講授課程號為c5的教師姓名。
select tn from t where exists (select * from tc where tno=t.tno and cno='c5')
[例]查詢沒有講授課程號為c5的教師姓名。
select tn from t where (not exists (select * from tc where tno=t.tno and cno='c5'))
SQL基礎3 子查詢
1 執行插入語句返回剛剛生成的自動編號 2 insert into tblclass output inserted.clsid values 大一一班 11 18 3 4 case函式用法 5 相當於switch 注意then後面的資料型別要一樣 6select from tblscore 7se...
sql 學習隨筆1 子查詢
資料如下 name val memo a 2 a2 a的第二個值 a 1 a1 a的第乙個值 a 3 a3 a的第三個值 b 1 b1 b的第乙個值 b 3 b3 b的第三個值 b 2 b2b2b2b2 b 4 b4b4 b 5 b5b5b5b5b5 建立表並插入資料 create table tb...
SQL多條件查詢子查詢SQL多條件查詢子查詢
多條件搜尋時where 1 1並不高效,如果使用這種方法,在資料庫中會做全表查詢 對每行資料都進行掃瞄比對 會無法使用索引等優化查詢的策略,建立的索引會暫時失效。case函式 case必須和end一起使用,下接when then select 數學成績 case when math 100 then...