-- 交叉連接產(chǎn)生笛卡爾值 (X*Y)
SELECT *
FROM Student
cross Join dbo.ClassInfo
--另外一種寫法
SELECT *
FROM Student , ClassInfo
-- 內(nèi)連接 (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 條件,允許有多個(gè),而且可能是針對(duì)某個(gè)表的
SELECT *
FROM Student
INNER JOIN dbo.ClassInfo ON dbo.Student.Class = dbo.ClassInfo.ID
AND dbo.Student.Class IN (1,2) -- 針對(duì)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;
-- 外連接和內(nèi)連接的區(qū)別是:
-- 內(nèi)連接,on條件不符合的話,會(huì)過(guò)濾掉數(shù)據(jù)
-- 外連接,以保留表為主,on條件成立顯示數(shù)據(jù),否則顯示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 去重復(fù)
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 多表連接查詢功能實(shí)例代碼,希望對(duì)大家有所幫助,如果大家有任何疑問(wèn)歡迎給我留言,小編會(huì)及時(shí)回復(fù)大家的!