程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 數據庫知識 >> 其他數據庫知識 >> MSSQL >> SQL Server 2012 多表銜接查詢功用實例代碼

SQL Server 2012 多表銜接查詢功用實例代碼

編輯:MSSQL

SQL Server 2012 多表銜接查詢功用實例代碼。本站提示廣大學習愛好者:(SQL Server 2012 多表銜接查詢功用實例代碼)文章只能為提供參考,不一定能成為您想要的結果。以下是SQL Server 2012 多表銜接查詢功用實例代碼正文


廢話不多說了,直接給大家貼代碼了,詳細代碼如下所示:

-- 穿插銜接發生笛卡爾值 (X*Y)
SELECT *
FROM  Student
    cross Join dbo.ClassInfo 
--另外一種寫法
SELECT *
FROM  Student , ClassInfo 
-- 內銜接 (Inner 可以省略)
SELECT *
FROM  Student
    JOIN dbo.ClassInfo ON dbo.Student.Class = dbo.ClassInfo.ID;
-- Inner Join
SELECT *
FROM  Student
    INNER JOIN dbo.ClassInfo ON dbo.Student.Class = dbo.ClassInfo.ID;
   -- on 條件,通常是 主外鍵,但是不限於主外鍵
   -- on 條件,允許有多個,而且能夠是針對某個表的
SELECT *
FROM  Student
    INNER JOIN dbo.ClassInfo ON dbo.Student.Class = dbo.ClassInfo.ID
    AND dbo.Student.Class IN (1,2) -- 針對Student表添加查詢條件
-- 不等於 (笛卡爾值減去 相等的值)
SELECT *
FROM  Student
    INNER JOIN dbo.ClassInfo ON dbo.Student.Class <> dbo.ClassInfo.ID;
--自銜接 從Class表中查詢到Class所在的系
SELECT T1.* ,T2.ClassName FROM dbo.ClassInfo AS T1
    INNER JOIN dbo.ClassInfo AS T2 ON T1.PID=T2.ID
-- Left Join
SELECT *
FROM  Student
    Left JOIN dbo.ClassInfo ON dbo.Student.Class = dbo.ClassInfo.ID;
-- Right Join
SELECT *
FROM  Student
    RIGHT  JOIN dbo.ClassInfo ON dbo.Student.Class = dbo.ClassInfo.ID;
-- 全外銜接
SELECT *
FROM  Student
    FULL OUTER JOIN dbo.ClassInfo ON dbo.Student.Class = dbo.ClassInfo.ID;
-- 外銜接和內銜接的區別是:
-- 內銜接,on條件不契合的話,會過濾掉數據
-- 外銜接,以保存表為主,on條件成立顯示數據,否則顯示NULL
--Union 縱向銜接
SELECT StuID,StuName,StuEnName,StuAge,StuBirthday
FROM  Student WHERE StuID<=2
UNION
SELECT StuID,StuName,StuEnName,StuAge,StuBirthday
FROM dbo.Student WHERE StuID>2
--Union 去反復
SELECT StuSex
FROM  Student WHERE StuID<=2
UNION
SELECT StuSex
FROM dbo.Student WHERE StuID>2
--Union 顯示全部
SELECT StuSex
FROM  Student WHERE StuID<=2
UNION ALL
SELECT StuSex
FROM dbo.Student WHERE StuID>2
--Except 差集,掃除
SELECT StuID,StuName,StuEnName,StuAge,StuBirthday
FROM  Student
Except
SELECT StuID,StuName,StuEnName,StuAge,StuBirthday
FROM dbo.Student WHERE StuID<=2
--Intersect 交集
SELECT StuID,StuName,StuEnName,StuAge,StuBirthday
FROM  Student WHERE StuID>=2
Except
SELECT StuID,StuName,StuEnName,StuAge,StuBirthday
FROM dbo.Student WHERE StuID<=3

以上所述是給大家引見的SQL Server 2012 多表銜接查詢功用實例代碼,希望對大家有所協助,假如大家有任何疑問歡送給我留言,會及時回復大家的!

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved