sql1:此时是正常的左连接
select user.name,dept.dept_name from user left join dept on dept.id= user.dept_id and dept.is_deleted='N' where user.is_delete='N'
此时将返回全部user并附带所属的单位(有可能有些user没有dept)
那假如想查出单位名为:“希望小学”的教师记录,但是不想使用inner join,那要怎么处理呢?此时看sql2
sql2:在where里过滤join表的条件,使其变成内连接
select user.name,dept.dept_name from user left join dept on dept.id= user.dept_id and dept.is_deleted='N'
where user.is_delete='N' and dept.dept_name='希望小学'
此时就只查出单位为“希望小学”的教师记录了,变成了inner join,实际上两者是一样的,mysql可能内部会自动转化成inner join,因为实测速度变快了为inner join的速度
select user.name,dept.dept_name from user inner join dept on dept.id= user.dept_id
and dept.dept_name='希望小学'
and dept.is_deleted='N' where user.is_delete='N'
这种动态left join变inner join方式可以用于mybatis,也是以上场景
select user.name,dept.dept_name from user left join dept on dept.id= user.dept_id and dept.is_deleted='N'
where user.is_delete='N'
<if test="et.deptName != null and et.deptName != ''">
and dept.dept_name like concat('%',#{et.deptName},'%')
</if>