例如:
一、将条件写在 left join on 后(在on关联查询之前做条件筛选,即第(2)中是table_a关联的是筛选完条件age=18之后的table_b表)
(1) on 后的 and 条件中主表( left 左边的表即 table_a )的条件不生效
select * from table_a a left join table_b b on a.name=b.name and a.age=18;
(2) on 后的 and 条件中从表( left 右边的表即 table_b )的条件会生效
select * from table_a a left join table_b b on a.name=b.name and b.age=18;
该SQL语句相当于是:
select * from table_a a left join (select * from table_b where age=18) b on a.name=b.name;
二、将条件写在 where 后(在关联查询之后做条件筛选,即table_a关联完table_b后的结果集中再做筛选)
select * from table_a a left join table_b b on a.name=b.name where a.age=18;
说明:left join on 后的 and 条件中 主表的条件不生效,从表的条件生效,并且从表先进行筛选后数据量可能变少,更便于与主表关联,有利于提高查询效率。
建议:主表的筛选条件放在 where 中,从表的 筛选条件放在 on 后的 and 中。