今天在sql优化的时候遇到了一个问题:
SELECT COUNT(1)
FROM (
SELECT
a.`namechn` AS na,
d.`namechn`,
d.`code`,
line.name ,
0 AS isdrive,
SUM(CASE WHEN p.number IS NULL THEN 0 ELSE p.number END) AS potent,
d.id ,
line.id AS lineId
FROM t_dealer AS d
LEFT JOIN t_dealer_potentialcustomer AS p ON d.`id`=p.`t_dealer_id`
INNER JOIN `t_org` AS a ON a.`id`=d.`t_org_rboid`
LEFT JOIN t_carline AS line ON p.t_carline_id=line.id
#WHERE p.isdel = 0 加上这句会把left join 出来的null 也给过滤掉
GROUP BY d.code, line.id
)AS X
WHERE potent=0
由于用的是left join 出来的数据全是null 所以对其进行sum() avg() 等操作的时候需要注意其值为null,还要注意where 语句里面的条件,由于它全为null很容易被过滤掉导致数据少了。