00时 00分 00秒

JOIN从句

MySQL基础表和数据

-- 5条数据
select * from test_a;

-- 8条数据
select * from test_b;

内连接

-- 内连接,join,为inner join的简化写法,产生A和B的交集。条数=A和B匹配的条数=4<=max(A条数, B条数)
select * from test_a a join test_b b on a.name = b.name; 

左外连接

-- 左外连接,left join,为left outer join的简化写法,产生表A的完全集,而B表中匹配的则有值,没匹配的以NULL值取代。条数=B中匹配A的条数+表A中未匹配的条数=4+3=7>=A表条数
select * from test_a a left join test_b b on a.name = b.name;

右外连接

-- 右外连接,right join,为right outer join的简化写法,产生表B的完全集,而A表中匹配的则有值,没匹配的以NULL值取代。条数=A中匹配B的条数+表B中未匹配的条数=4+4=8>=B表条数
select * from test_a a right join test_b b on a.name = b.name;
-- 等效如下
select * from test_b b left join test_a a on test_a.name = test_b.name;

全连接

MySQL并不支持 full join 操作,可以使用左连接 union all 右连接的方式来达到这个效果,条数为左连接条数 + 右连接条数 = 15

select * from test_a a left join test_b b on a.name = b.name
union all
select * from test_a a right join test_b b on a.name = b.name;

笛卡尔连接

又称交叉连接,一般情况下很少使用

-- A和B的笛卡尔集,即A的每一条都和B的每一条关联,所以条数为A * B,示例中是5 * 8 = 40
select count(*) from test_a a cross join test_b b;
-- 通过过滤条件达到内连接的效果
select * from test_a a cross join test_b b where a.name = b.name;

on and和on where的区别

在使用left join时,on and和on where条件的区别如下:  
1、on条件是在生成临时表时使用的条件,它不管on中的条件是否为真,都会返回左边表中的记录。

(实际上左连接中如果有and语句是对左表进行过滤的,那么不管真假都不起任何作用。如果是对右表过滤的,那么左表所有记录都返回,右表筛选以后再与左表连接返回,即on and只能对右表过滤)  
2、where条件是在临时表生成好后,再对临时表进行过滤的条件(一般使用为对最左表的过滤)。这时已经没有left join的含义(必须返回左边表的记录)了,条件不为真的就全部过滤掉,on后的条件用来生成左右表关联的临时表,where后的条件对临时表中的记录进行过滤。

-- 第一条语句比较好理解,筛选之后跟左表连接,第二条语句输出同第一条,说明on and即是对右表进行过滤,建议使用第二条这一种(易读)
select * from test_a a left join (select * from test_b where name = '香蕉') b on b.name = a.name order by a.id;
select * from test_a a left join test_b b on b.name = a.name and b.name = '香蕉' order by a.id;
-- 第一条语句比较好理解,筛选之后跟右表连接,第二条语句输出同第一条,说明on where一般对左表进行过滤,建议使用第二条这一种(易读)
select * from (select * from test_a where name = '香蕉') a left join test_b b on a.name = b.name;
select * from test_a a left join test_b b on a.name = b.name where a.name = '香蕉';

在使用inner join时,不管是对左表还是右表进行筛选,on and和on where都会对生成的临时表进行过滤。

posted @ 2018-04-02 10:59  杰克思勒(Jacksile)  阅读(484)  评论(0编辑  收藏  举报