首页 > 解决方案 > 为什么 SQL 中的最后一行会有所不同

问题描述

我正在尝试选择广告曝光的某些部分

有2个相似的SQL代码,只有一行不同,但输出不同

代码1

select req.bucket
,imp.expo_freq
,imp.platform
from some_adform imp
left join some_other_adform req
    on imp.requestid=req.requestid
where req.lineitemid!='something'
;

代码2

select req.bucket
,imp.expo_freq
,imp.platform
from some_adform imp
left join some_other_adform req
    on imp.requestid=req.requestid
;

这两个部分之间的唯一区别显然是 (where req.lineitemid!='something') ,那么 imp 表中的 expo_freq 是不同的。但是经过检查,在 some_other_adform req 表中,'something' 根本不存在,这意味着它应该影响任何东西!那么为什么这条线会影响 SQL 的答案呢?顺便说一句,如果我将行放在 req 表单中,结果将与 code1 相同,代码 3 看起来像这样

select req.bucket
,imp.expo_freq
,imp.platform
from some_adform imp
left join (select * from some_other_adform where req.lineitemid!='something') req
    on imp.requestid=req.requestid
;

标签: sql

解决方案


因为当将语句放在 where 子句中时,这意味着表中必须有左连接的行才能评估语句 - 实际上使其成为内部连接。

如果将其作为左连接的条件(如 AND ...),则仅对左连接表中的匹配行进行评估:

select req.bucket,imp.expo_freq,imp.platform
from some_adform imp
left join some_other_adform req
  on imp.requestid=req.requestid
  and req.lineitemid!='something';

作为旁注,如果您添加了 NULL 检查,您将得到相同的结果:

select req.bucket,imp.expo_freq,imp.platform
from some_adform imp
left join some_other_adform req
  on imp.requestid=req.requestid
where ISNULL(req.lineitemid,'')!='something';

推荐阅读