今天講下T-sql中用于查詢的表關聯和視圖,我們平時做項目的時候會遇到一些復雜的查詢操作,比如有班級表,學生表,現在要查詢一個學生列表,要求把學生所屬班級名稱也查詢出來,這時候簡單的select查詢就不行了,需要關聯班級表,因為學生是一定屬于某一個班級的,所以關聯的示例需要自關聯。
表關聯(join)
下面列一些示例代碼,幫助大家理解。
select t2. * -- 表自關聯 from Tree t1 inner join Tree t2 on t1.NO = t2.ParentNo where t1.Name = ' Node1_2 ' ; select * from tree -- 子嵌套查詢 where ParentNo = ( select NO from tree where Name = ' Node1_2 ' ); select * from tree where parentNo in ( select no from tree where Name = ' Node1_2 ' );
上面是表自關聯,關鍵字inner,就是返回t1.NO = t2.ParentNo 條件的所有t2表的數據,
有表自關聯,當然還有左關聯,右關聯,示例代碼:
select t2. * -- 左關聯 from Tree t1 left join Tree t2 on t1.NO = t2.ParentNo where t1.Name = ' Node1_2 ' ; select t2. * -- 右關聯 from Tree t1 right join Tree t2 on t1.NO = t2.ParentNo where t1.Name = ' Node1_2 ' ;
視圖View
視圖的關鍵字是View,就是一個查詢集合,方便我們去查詢數據,視圖其實就是表,多表連接的表,我們查詢的時候不需要反復的去拼接語句,直接查詢視圖就可以,方便我們的操作,當然一些簡單的查詢操作就沒必要去創建視圖了。
示例代碼:
create view Production.vw_Product as select t1. * from Production.Product t1 left outer join Production.ProductModel t2 on t2.ProductModelID = t1.ProductModelID left outer join Production.ProductSubcategory t3 on t3.ProductSubcategoryID = t1.ProductSubcategoryID left outer join Production.UnitMeasure t4 on t4.UnitMeasureCode = t1.SizeUnitMeasureCode and t4.UnitMeasureCode = t1.SizeUnitMeasureCode -- order by t1.ProductID
查詢視圖:
select * from Production.vw_Product
表關聯和視圖都是比較簡單的數據庫操作,但也是比較常用的。大家好好練習。
還有一些相關編程知識的整理,希望大家關注下。。。
?
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
