理论不多说,通过一个实际栗子来说明一下多表关联时,不同where条件带来的结果有哪些差异,从而明确在不同需求的前提下,应该怎样进行查询。
需求:用户的支付时间与登录时间的差值
查询1:select t1.user_id, datediff ( t2.pay_date,t1.login_date) as datebetween
from
(select user_id,login_date from 表1)t1
join
(select user_id,pay_date from 表2 where pay_date is not null)t2
on t1.user_id = t2.user_id
查询2:select t1.user_id, datediff ( t2.pay_date,t1.login_date) as datebetween
from
(select user_id,login_date from 表1)t1
join
(select user_id,pay_date from 表2)t2
on t1.user_id = t2.user_id
where t2.pay_time is not null
这两种查询结果并没有任何不同之处,于是许多人,在查询时会掉进这样的坑里:
需求:非广告用户的支付与登录时间的差值
查询1:select t.user_id, datediff ( t2.pay_date,t.login_date) as datebetween
(select t1.user_id as user_id, t1. login_date as login_date
from
(select user_id,login_date from 表1)t1
left join
(select user_id, commercial from 表3 where t2.commercial < > 0)t3
on t1.user_id = t2.user_id)t
join
(select user_id,pay_date from 表2 where pay_date is not null)t2
on t.user_id=t2.user_id
查询2:select t.user_id, datediff ( t2.pay_date,t.login_date) as datebetween
(select t1.user_id as user_id, t1. login_date as login_date
from
(select user_id,login_date from 表1)t1
left join
(select user_id, commercial from 表3)t3
on t1.user_id = t2.user_id
where t2.commercial < > 0)t
join
(select user_id,pay_date from 表2 where pay_date is not null)t2
on t.user_id=t2.user_id
由于表3并不包含所有用户,因此表1关联表3需使用left join。
此时,查询一虽然对表3做了限制,但关联结果仍是所有用户,因此查询1最终的结果是错误的。而查询2是对表1关联表3 的结果t使用where条件进行筛选,再去关联表2,这个查询结果才是正确的。
不知道有没有类似的情况,在第一种查询的方式下得到正确的结果,而使用第二种查询反而会得到错误的结果,哪位小伙伴如有相似经历,还请多多指教。