学习内容参考来源:www.runoob.com
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','*','*.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张数据表:
website
access_log
再看一下join后的结果:
INNER JOIN
select * from website t1 inner join access_log t2 on t1.id= t2.site_id;
-- 只有左表、右表完全匹配的记录才能被返回;
LEFT JOIN
select * from website t1 left join access_log t2 on t1.id= t2.site_id;
--即使右表没有匹配,也会返回左表的所有行;
RIGHT JOIN
select * from website t1 right join access_log t2 on t1.id= t2.site_id;
--即时左表没有匹配,也会返回右表的所有行;
FULL JOIN
select * from website t1 FULL join access_log t2 on t1.id= t2.site_id;
--左表、右表不管是否匹配,返回俩表的所有行;