原理:
左关联时会先创建临时表t1和t2,where后面的条件会先过滤t1、t2临时表后在关联,on后面的条件会先关联t1、t2后在过滤。
结论:
条件在on后面,主表数据量不变,副表只显示符合条件的。
条件在where后面,先过滤条件在关联。
测试时直接替换dmp库就可以执行
use dmp;
create table dmp.yl_test_1(id int,name string);
create table dmp.yl_test_2(id int,age int);
insert into dmp.yl_test_1 values(1,'aa');
insert into dmp.yl_test_1 values(2,'bb');
insert into dmp.yl_test_1 values(3,'cc');
insert into dmp.yl_test_2 values(1,40);
insert into dmp.yl_test_2 values(2,50);
条件放在on和where后面的区别:
表1
id,name
1,aa
2,bb
3,cc
表2
id,num
1,40
2,50
select * from dmp.yl_test_1 t1
left join
dmp.yl_test_2 t2 on t1.id = t2.id and t1.id = 3;
id name id_1 age
1 aa
2 bb
3 cc
select * from dmp.yl_test_1 t1
left join
dmp.yl_test_2 t2 on t1.id = t2.id where t1.id = 3;
id name id_1 age
3 cc
select * from dmp.yl_test_1 t1
left join
dmp.yl_test_2 t2 on t1.id = t2.id and t2.id = 3;
id name id_1 age
1 aa
2 bb
3 cc
select * from dmp.yl_test_1 t1
left join
dmp.yl_test_2 t2 on t1.id = t2.id where t2.id = 3;
id name id_1 age