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

SQL Server 2012 多表連接查詢功能實例代碼,sql2012

編輯:更多數據庫知識

SQL Server 2012 多表連接查詢功能實例代碼,sql2012


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

-- 交叉連接產生笛卡爾值 (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. No
Copyright © 程式師世界 All Rights Reserved