sql join 大彙總(inner join 內聯、full join 全連、 left join 左連、right join 右連 、cross join 交叉連以及union)
一、定義兩個表 ,結構如下
create table A (
id nvarchar(50) null,
names nvarchar(50) null
)
create table B (
id nvarchar(50) null,
names nvarchar(50) null
)
二、 插入資料
A表
insert into A values('1','zhangsan00');
insert into A values('2','zhangsan01');
insert into A values('3','zhangsan02');
insert into A values('4','zhangsan03');
B表
insert into B values('1','zhangsan00');
insert into B values('2','zhangsan01');
insert into B values('3','zhangsan05');
insert into B values('4','zhangsan06');
-- inner join 兩個表的交集
select *from A inner join B on A.names=B.names
-- full out join 兩個表的並集
select * from A full outer join B on A.names=B.names
-- 案例 求兩個表的非交集部分
select * from A full outer join B on A.names = B.names where A.id is null or B.id is null
--left join 左表的所有資料列出,右表的相同部分列出,不同部分用null 補齊
select A.*,B.id as Bid,B.names as bName from A left join B on A.names =B.names;
--right join 右表的所有資料列出,左表相同部分列出,不同部分用null 補齊
select A.*,B.id as Bid,B.names as bName from A right join B on a.names = b.names
--union 合併兩個表的資料(不允許重複)
select names from A
union
select names from B
--union all 兩個表的並集(語序重複)
select names from A
union all
select names from B
-- corss join 表A和表B的資料進行一個N*M的組合,即笛卡爾積
select * from A cross join B