代碼如下復制代碼
-- 交叉連接產生笛卡爾值 (X*Y)
SELECT*
FROM Student
crossJoindbo.ClassInfo
--另外一種寫法
SELECT*
FROM Student , ClassInfo
-- 內連接 (Inner 可以省略)
SELECT*
FROM Student
JOINdbo.ClassInfoONdbo.Student.Class = dbo.ClassInfo.ID;
-- Inner Join
SELECT*
FROM Student
INNERJOINdbo.ClassInfoONdbo.Student.Class = dbo.ClassInfo.ID;
-- on 條件,通常是 主外鍵,但是不限於主外鍵
-- on 條件,允許有多個,而且可能是針對某個表的
SELECT*
FROM Student
INNERJOINdbo.ClassInfoONdbo.Student.Class = dbo.ClassInfo.ID
ANDdbo.Student.ClassIN(1,2)-- 針對Student表增加查詢條件
-- 不等於 (笛卡爾值減去 相等的值)
SELECT*
FROM Student
INNERJOINdbo.ClassInfoONdbo.Student.Class <> dbo.ClassInfo.ID;
--自連接 從Class表中查詢到Class所在的系
SELECTT1.* ,T2.ClassNameFROMdbo.ClassInfoAST1
INNERJOINdbo.ClassInfoAST2ONT1.PID=T2.ID
-- Left Join
SELECT*
FROM Student
LeftJOINdbo.ClassInfoONdbo.Student.Class = dbo.ClassInfo.ID;
-- Right Join
SELECT*
FROM Student
RIGHT JOINdbo.ClassInfoONdbo.Student.Class = dbo.ClassInfo.ID;
-- 全外連接
SELECT*
FROM Student
FULLOUTERJOINdbo.ClassInfoONdbo.Student.Class = dbo.ClassInfo.ID;
-- 外連接和內連接的區別是:
-- 內連接,on條件不符合的話,會過濾掉數據
-- 外連接,以保留表為主,on條件成立顯示數據,否則顯示NULL
--Union 縱向連接
SELECTStuID,StuName,StuEnName,StuAge,StuBirthday
FROM StudentWHEREStuID<=2
UNION
SELECTStuID,StuName,StuEnName,StuAge,StuBirthday
FROMdbo.StudentWHEREStuID>2
--Union 去重復
SELECTStuSex
FROM StudentWHEREStuID<=2
UNION
SELECTStuSex
FROMdbo.StudentWHEREStuID>2
--Union 顯示全部
SELECTStuSex
FROM StudentWHEREStuID<=2
UNIONALL
SELECTStuSex
FROMdbo.StudentWHEREStuID>2
--Except 差集,排除
SELECTStuID,StuName,StuEnName,StuAge,StuBirthday
FROM Student
Except
SELECTStuID,StuName,StuEnName,StuAge,StuBirthday
FROMdbo.StudentWHEREStuID<=2
--Intersect 交集
SELECTStuID,StuName,StuEnName,StuAge,StuBirthday
FROM StudentWHEREStuID>=2
Except
SELECTStuID,StuName,StuEnName,StuAge,StuBirthday
FROMdbo.StudentWHEREStuID<=3