七种join的书写规范
在mysql中的两表进行连接时,总共有7种连接情况,具体可见下图
由图的从左到右的顺序
图1.左连接(left join):返回左表中的所有记录和右表中的连接字符字段相等的记录,若右表没有匹配值则补NULL
图2.右连接(right join):返回右表中的所有记录和右表中的连接字符字段相等的记录,若左表没有匹配值则补NULL
图3.内连接(inner join):只有满足条件的巨鹿才会出现在查询结果中,即左表和右表的公共部分
图4.左表中的独自拥有的部分,去除与右表中的重合部分
图5.右表中的独自拥有的部分,去除与左表中的重合部分
图6.左表和右表的重合部分,以及左右表的重和部分(可以看成两表的左连接和右连接的拼接)
图7.左表和右表的独自拥有部分(可以看成是图4和图5的拼接)
实例详解:
创建相关表以及插入数据
create table student(
sid int(11) primary key auto_increment,
sname varchar(20) not null,
class_id int(11) null
);
create table class(
cid int(11) primary key,
cname varchar(20) not null
);
alter table student add foreign key(class_id) references class(cid);
desc student;
insert into class(cid,cname) values
(1,'一年级'),
(2,'二年级'),
(3,'三年级'),
(4,'四年级'),
(5,'五年级'),
(6,'六年级');
set sql_safe_updates = 0;
insert into student(sid,sname,class_id) values
(1,'张三',1),
(2,'李四',4),
(3,'王五',1),
(4,'赵柳',2),
(5,'孙权',6),
(6,'钱升',null),
(7,'刘备',3),
(8,'周往',5);
#内连接
select
student.*,
class.*
from
student
inner join class
on student.class_id = class.cid;
#左连接
select
student.*,
class.*
from
student
left join class
on student.class_id = class.cid;
#右连接
select
student.*,
class.*
from
student
right join class
on student.class_id = class.cid;
#student数据表锁独有的数据
select
student.*,
class.*
from
student
left join class
on student.class_id = class.cid
where class.cid is null;
#class表锁独有的数据
select
student.*,
class.*
from
student
right join class
on student.class_id = class.cid
where student.class_id is null;
select
student.*,
class.*
from
student
left join class
on student.class_id = class.cid
union
select
student.*,
class.*
from
student
right join class
on student.class_id = class.cid;
select
student.*,
class.*
from
student
left join class
on student.class_id = class.cid
where class.cid is null
union
select
student.*,
class.*
from
student
right join class
on student.class_id = class.cid
where student.class_id is null;
笨鸟先飞