我有像这样的查询
SELECT f.ACCOUNT_ID,
f.TGL,
p.ACCOUNT_EMAILADDRESS
FROM distributor_kokola.forecast f
inner join distributor_kokola.push_distributor p on p.ACCOUNT_ID = f.ACCOUNT_ID
where f.ACCOUNT_ID NOT IN(
select ACCOUNT_ID
from distributor_kokola.forecast
where DATE_FORMAT(TGL, "%Y-%m") = DATE_FORMAT(CURDATE(), "%Y-%m")
group by ACCOUNT_ID
)
group by f.ACCOUNT_ID;
Sub Query工作但是要慢,所以我用Left Join更改它,它运行得更快
SELECT f.ACCOUNT_ID,
f.TGL,
p.ACCOUNT_EMAILADDRESS
FROM distributor_kokola.forecast f
left join(
select ACCOUNT_ID
from distributor_kokola.forecast
where DATE_FORMAT(TGL, "%Y-%m") = DATE_FORMAT(CURDATE(), "%Y-%m")
group by ACCOUNT_ID
)subb on subb.ACCOUNT_ID = f.ACCOUNT_ID
inner join distributor_kokola.push_distributor p on p.ACCOUNT_ID = f.ACCOUNT_ID
group by f.ACCOUNT_ID;
但是,我的问题仍然是包含错误结果,
使用Not IN,查询1选择NOT IN query 2。
如何通过左连接获得NOT IN查询。
任何人都可以帮助我吗?
感谢。
答案 0 :(得分:1)
您必须添加WHERE子句,以便根据LEFT JOIN
的结果进行过滤。如果添加适当的WHERE子句WHERE subb.ACCOUNT_ID IS NULL
,它应该按预期工作(因为您在子查询中使用了GROUP BY
,没有重复行的危险):
SELECT f.ACCOUNT_ID,
f.TGL,
p.ACCOUNT_EMAILADDRESS
FROM distributor_kokola.forecast f
left join(
select ACCOUNT_ID
from distributor_kokola.forecast
where DATE_FORMAT(TGL, "%Y-%m") = DATE_FORMAT(CURDATE(), "%Y-%m")
group by ACCOUNT_ID
) subb on subb.ACCOUNT_ID = f.ACCOUNT_ID
inner join distributor_kokola.push_distributor p on p.ACCOUNT_ID = f.ACCOUNT_ID
WHERE sub.ACCOUNT_ID IS NULL
group by f.ACCOUNT_ID;
<强>更新强>
我们LEFT JOIN
的目标是找到forecast
表中所有在子查询中没有匹配行的行。因此,我们需要一个WHERE
子句来删除具有匹配行的所有行 - WHERE sub.ACCOUNT_ID IS NULL
非常适合。
SO用户@quassnoi写了一个wonderful comparison of different methods来实现这个目标。