列值子查詢
阿新 • • 發佈:2018-11-10
與標量子查詢不同,列值子查詢可以返回一個多行多列的結果集。這樣的子查詢又被稱為表子查詢,表子查詢可以看作一個臨時的表,表子查詢可以用在SELECT 語句的FROM子句中、INSERT語句、連線、IN 子句等很多場合。
首先來看一個在FROM子句中使用的最簡單的表子查詢。SQL語句如下:
SELECT T_Reader.FName,t2.FYearPublished,t2.FName FROM T_Reader,(SELECT * FROM T_Book WHERE FYearPublished < 1800) t2
這裡將T_Reader表和表子查詢做交叉連線,並且將“SELECT * FROM T_Book WHERE FYearPublished < 1800”做為表子查詢,還可以為表子查詢執行表別名,在SELECT的列表中也可以使用和表一樣的列名飲用方式,這與使用一個普通的資料表沒有什麼區別。
執行完畢我們就能在輸出結果中看到下面的執行結果:
FName FYearPublished FName Tom 1700 History of America Sam 1700 History of America Jerry 1700 History of America Lily 1700 History of America Marry 1700 History of America Kelly 1700 History of America Tim 1700 History of America King 1700 History of America John 1700 History of America Lucy 1700 History of America July 1700 History of America Fige 1700 History of America Tom 1771 How To Singing Sam 1771 How To Singing Jerry 1771 How To Singing Lily 1771 How To Singing Marry 1771 How To Singing Kelly 1771 How To Singing Tim 1771 How To Singing King 1771 How To Singing John 1771 How To Singing Lucy 1771 How To Singing July 1771 How To Singing
表子查詢可以看作一張臨時的表,所以引用子查詢中列的時候必須使用子查詢中定義的列名,也就是如果子查詢中為列定義了別名,那麼在引用的時候也要使用別名。比如下面的SQL語句:
SELECT T_Reader.FName,t2.FYear,t2.FName ,t2.F3 FROM T_Reader,(SELECT FYearPublished AS FYear,FName,1+2 as F3 FROM T_Book WHERE FYearPublished < 1800) t2
這裡的表子查詢為FYearPublished列取了一個別名FYear,這樣在引用它的時候就必須使用FYear而不能繼續使用FYearPublished這個名字,這裡子查詢中還增加了一個新列F3,同樣可以在SELECT列表中引用它。
執行完畢我們就能在輸出結果中看到下面的執行結果:
FName FYear FName F3
Tom 1700 History of America 3
Sam 1700 History of America 3
Jerry 1700 History of America 3
Lily 1700 History of America 3
Marry 1700 History of America 3
Kelly 1700 History of America 3
Tim 1700 History of America 3
King 1700 History of America 3
John 1700 History of America 3
Lucy 1700 History of America 3
July 1700 History of America 3
Fige 1700 History of America 3
Tom 1771 How To Singing 3
Sam 1771 How To Singing 3
Jerry 1771 How To Singing 3
Lily 1771 How To Singing 3
Marry 1771 How To Singing 3
Kelly 1771 How To Singing 3
Tim 1771 How To Singing 3
King 1771 How To Singing 3
John 1771 How To Singing 3
Lucy 1771 How To Singing 3
July 1771 How To Singing 3