SQL Left、Right Join等操作符總結,leftjoin

來源:互聯網
上載者:User

SQL Left、Right Join等操作符總結,leftjoin
1、在tableA與tableB中查詢tableA中全部資料和tableB中在tableA中的資料
select * from tableA A left join tableB B on A.key=B.key
2、在tableA中查詢排除tableB中資料,剩餘的tableA中的資料
select * from tableA A left join tableB B on A.key=B.key where B.key is null
3、查詢tableA與tableB中所有的資料
select * from tableA A full outer join tableB B on A.key=B.key
4、查詢tableA與tableB兩表之外的資料
select * from tableA A full outer join tableB B on A.key=B.key where A.key is null or B.key is null
5、查詢tableA與tableB中共同的資料
select * from tableA A inner join tableB B on A.key=B.key
簡述sql中inner join、left join、right join的功可以

與其解釋,其實不許直接寫個例子給你看,或許你能更快理解
建兩個表 A和B,A表包含包含一個欄位Aid;B表包含兩個欄位Aid,Bid
create table A (aid int)
create table B (aid int ,bid int)
分別插入資料
向A表aid欄位插入1,再向A表aid欄位插入2
向B表aid欄位插入1,bid欄位插入2
向B表aid欄位插入3,bid欄位插入4
insert into a (aid) values (1)
insert into a (aid) values (2)
insert into b(aid,bid) values (1,2)
insert into c(aid,bid) values (3,4)
那麼 分別用inner join,left jion,right join 來關聯一下看看就知道他們的作用和區別了
select a.aid,b.aid,b.bid from a inner join b on a.aid=b.aid
得出結果 1,1,2
select a.aid,b.aid,b.bid from a left join b on a.aid=b.aid
得出結果
1,1,2
2, ,
select a.aid,b.aid,b.bid from a right join b on a.aid=b.aid
得出結果
1,1,2
,3,4
也就是說,
inner join取的,是關聯欄位on a.aid=b.aid 的等號兩邊都合格值
left join取的,是關聯欄位on a.aid=b.aid的左邊符合的值,如果左邊有值右邊沒有相符的,以null補齊
right join 取的,是關聯欄位on a.aid=b.aid的右邊符合的值,同樣,如果右邊有值而左邊沒有相符的,那麼同樣以null空值補齊
 
sql語句中join ,left join ,right join有什不同

left join :左串連,返回左表中所有的記錄以及右表中串連欄位相等的記錄。
right join :右串連,返回右表中所有的記錄以及左表中串連欄位相等的記錄。
inner join: 內串連,又叫等值串連,只返回兩個表中串連欄位相等的行。
full join:外串連,返回兩個表中的行:left join + right join
cross join:結果是笛卡爾積,就是第一個表的行數乘以第二個表的行數。

declare @a table(a int,b int)
declare @b table(a int,b int)

insert @a values(1,1)
insert @a values(2,2)
insert @b values(1,1)
insert @b values(3,3)
select * from @a
select * from @b
--左:
select * from @a Aa left join @b Bb on Aa.a=Bb.a
--右:
select * from @a Aa right join @b Bb on Aa.a=Bb.a
--內
select * from @a Aa inner join @b Bb on Aa.a=Bb.a
--外:
select * from @a Aa full join @b Bb on Aa.a=Bb.a
--交叉串連
select * from @a cross join @b
 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.