SQL語法學習記錄——JOIN

學習內容參考來源:www.runoob.comweb

JOIN準備

--爲了方便練習,在數據庫中建立演示數據:
create database TEST;
use TEST ;
----------
go
--創建[網站信息表],能夠視做基礎資料表;
create table website 
 (id int primary key,
  name varchar(255),
  url varchar(255),
  alexa varchar(255),
  country varchar(255)
  )
insert into website values 
('1','google','www.google.com','1','USA')
,('2','淘寶','www.taobao.com','13','CN')
,('3','菜鳥教程','www.runoob.com','4689','CN')
,('4','微博','weibo.com','20','CN')
,('5','Facebook','www.facebook.com','3','USA')
,('6','stackoverflow','stackoverflow.com','0','IND')
,('7','小米','www.mi.com','50','CN')
select * from website;
----------
--創建[網站日誌表],能夠視做出入庫明細表;
create table access_log
 (id int primary key,
  site_id int not null,
  [count] int not null,
  date date not null
  )
insert into access_log values 
(1,1,45,'2016-05-10')
,(2,3,100,'2016-05-13')
,(3,1,230,'2016-05-14')
,(4,2,10,'2016-05-14')
,(5,5,205,'2016-05-14')
,(6,4,13,'2016-05-15')
,(7,3,220,'2016-05-15')
,(8,5,545,'2016-05-16')
,(9,3,201,'2016-05-17')
,(10,8,299,'2016-05-18')
select * from access_log;

JOIN類型

  • INNER JOIN: 只有左表、右表徹底匹配的記錄才能被返回;
  • LEFT JOIN:即便右表沒有匹配,也會返回左表的全部行;
  • RIGHT JOIN:即時左表沒有匹配,也會返回右表的全部行;
  • FULL JOIN:左表、右表無論是否匹配,返回倆表的全部行;

JOIN結果

先看一下演示的2張數據表:sql

website數據庫

website

access_log學習

access_log

再看一下join後的結果:網站

INNER JOIN

select * from  website t1 inner join access_log t2 on t1.id= t2.site_id;
-- 只有左表、右表徹底匹配的記錄才能被返回;

inner join

這裏寫圖片描述

LEFT JOIN

select * from  website t1 left join access_log t2 on t1.id= t2.site_id;
--即便右表沒有匹配,也會返回左表的全部行;

left join

這裏寫圖片描述

RIGHT JOIN

select * from  website t1 right join access_log t2 on t1.id= t2.site_id;
--即時左表沒有匹配,也會返回右表的全部行;

right join

這裏寫圖片描述

FULL JOIN

select * from  website t1 FULL join access_log t2 on t1.id= t2.site_id;
--左表、右表無論是否匹配,返回倆表的全部行;

FULL JOIN

這裏寫圖片描述

相關文章
相關標籤/搜索