前置条件
创建数据库,创建测试表,插入测试数据
create database test;
use test
create table testJoin_one(
id int(5),
t_desc varchar(200));
insert into testJoin_one(id,t_desc) values(1,'孙悟空'),(3,'沙悟净'),(5,'猪八戒');
create table testJoin_two(
id int(5),
t_desc varchar(200));
insert into testJoin_two(id,t_desc) values(1,'鲁智深'),(2,'林冲'),(4,'吴用');
create table testJoin_three(
id int(5),
t_desc varchar(200));
insert into testJoin_three(id,t_desc) values(2,'刘备'),(5,'关羽'),(7,'张飞');
测试相关命令
一次查询(单个join)
-
select * from testJoin_one a inner join testJoin_two b on a.id=b.id;
-
select * from testJoin_one a left join testJoin_two b on a.id=b.id;
-
select * from testJoin_one a right join testJoin_two b on a.id=b.id;
总结
- inner join 表示join两边的表都有比较的值时保留记录,不满足则排除。
- left join 表示 向 join 的左边看齐,如果右边没有对应的记录,以null填充
- right join 表示 向 join 的右边看齐,如果左边没有对应的记录,以null填充
两次查询(两个join)
-
select * from testJoin_one a inner join testJoin_two b on a.id=b.id inner join testJoin_three c on a.id=c.id;
-
select * from testJoin_one a inner join testJoin_two b on a.id=b.id right join testJoin_three c on a.id=c.id;
-
select * from testJoin_one a inner join testJoin_two b on a.id=b.id left join testJoin_three c on a.id=c.id;
-
select * from testJoin_one a right join testJoin_two b on a.id=b.id inner join testJoin_three c on a.id=c.id;
-
select * from testJoin_one a right join testJoin_two b on a.id=b.id right join testJoin_three c on a.id=c.id;
-
select * from testJoin_one a right join testJoin_two b on a.id=b.id left join testJoin_three c on a.id=c.id;
-
select * from testJoin_one a left join testJoin_two b on a.id=b.id inner join testJoin_three c on a.id=c.id;
-
select * from testJoin_one a left join testJoin_two b on a.id=b.id right join testJoin_three c on a.id=c.id;
-
select * from testJoin_one a left join testJoin_two b on a.id=b.id left join testJoin_three c on a.id=c.id;
总结
两个join 的情况是根据左右顺序依次执行,右边的join 执行的是左边join执行之后的结果集。
举个例子
select * from testJoin_one a left join testJoin_two b on a.id=b.id right join testJoin_three c on a.id=c.id;
此处,先执行的是select * from testJoin_one a left join testJoin_two b on a.id=b.id
,它的执行结果是
在此基础上执行right join 操作,此时比对a.id和c.id 可以发现只有5 满足,故结果是