SQL关联查询中on与where

微信公众号:刺刺刺猬的优雅

前段时间,做一个查询,打算用left join查询存在于A表但不存在于B表记录,但怎么查都不对,原因是把所有filter全部放在了where语句中,因此回头看了资料,记录一下。


on 条件是在join之前生效,因此无论后面是什么条件都会返回左表所有记录。

where 条件是在完成join后再生效。


下面进行测试:

表t1描述学生姓名和年龄:

表t2描述学生姓名和分数:

****************************SQL1*******************************

select t1.*,'*******' as "华丽分割",t2.*

from sherry.t1 t1

left join sherry.t2 t2 on t1.st_name = t2.st_name and t1.st_name = 'emma';

****************************SQL2*******************************

select t1.*,'*******' as "华丽分割",t2.*

from sherry.t1 t1

left join sherry.t2 t2 on t1.st_name = t2.st_name and t2.st_name = 'sharon';

****************************SQL3*******************************

select t1.*,'*******' as "华丽分割",t2.*

from sherry.t1 t1

left join sherry.t2 t2 on t1.st_name = t2.st_name

where t1.st_name = 'emma';

****************************SQL4*******************************

select t1.*,'*******' as "华丽分割",t2.*

from sherry.t1 t1

left join sherry.t2 t2 on t1.st_name = t2.st_name 

where t2.st_name = 'sharon';


总结:

不管on上的条件是否为真都会返回left或right表中的记录,full则具有left和right的特性的并集。 而inner jion没这个特殊性,则条件放在on中和where中,返回的结果集是相同的。但是建议无论是哪种关联方式,都安装严格的格式来写。

猜你喜欢

转载自www.cnblogs.com/guoxueyuan/p/9084389.html