T-SQL高級查詢語句(父子查詢)


 1  T-SQL高級查詢語句
 2 
 3 高級查詢
 4 
 5 1.連接查詢,對結果集列的擴展
 6 select * from info
 7 
 8 select * from info,nation #形成笛卡爾積
 9 select * from info,nation where info.nation=nation.code
10 select info.code,info.name,sex,nation.name,birthday from info,nation where info.nation=nation.code
11 
12 select * from info join nation on info.nation=nation.code
13 
14 2.聯合查詢,對結果集行的擴展
15 select code,name from info
16 union
17 select code,name from nation

 1 3.子查詢
 2 
 3 父查詢:外層查詢
 4 子查詢:里層查詢
 5 
 6 子查詢的結果做為父查詢的條件
 7 
 8 (1)無關子查詢
 9 子查詢在執行的時候和父查詢沒有關系,子查詢可以單獨執行
10 
11 1.查詢民族為‘漢族’的所有人員信息
12 父查詢:select * from info where nation=()
13 子查詢:select code from nation where name='漢族'
14 
15 select * from info where nation=(select code from nation where name='漢族')

 1 2.查詢系列名為‘寶馬5系’的所有汽車信息 2 select * from car where brand=(select brand_code from brand where brand_name='寶馬5系') 

 

1 (2)相關子查詢
2 子查詢在執行的時候和父查詢有關系,子查詢不可以單獨執行
3 
4 1.查詢汽車表中油耗小於該系列平均油耗的所有汽車信息
5 父查詢:select * from car where oil<(該系列平均油耗)
6 子查詢:select avg(oil) from car where brand=該系列
7 
8 select * from car as a where oil<(select avg(oil) from car as b where b.brand=a.brand)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM