刚开始做项目对于left join的细节还不太注意,
SELECT
g.dict_note AS device_type,
a.deviceCount AS device_count,
a.endCount AS end_count,
a.description AS description
FROM
(
SELECT
device_type,
COUNT(*) AS deviceCount,
COUNT(IF(use_end_time <NOW(),TRUE,NULL) )AS endCount,
description
FROM t_cfg_device WHERE device_use_state = 1 and isdel = 0
GROUP BY device_type
AS a
LEFT JOIN t_cfg_dict AS g ON a.device_type = g.dict_code where g.col_name = 'device_type'
最后一句LEFT JOIN t_cfg_dict AS g ON a.device_type = g.dict_code where g.col_name = 'device_type'的where让我的endcount统计的结果不对,改了以后就成功了
数据库在通过连接两张或多张表来返回记录时,都会生成一张中间的临时表,然后再将这张临时表返回给用户。
在使用left jion时,on和where条件的区别如下:
1、 on条件是在生成临时表时使用的条件,它不管on中的条件是否为真,都会返回左边表中的记录。
2、where条件是在临时表生成好后,再对临时表进行过滤的条件。这时已经没有left join的含义(必须返回左边表的记录)了,条件不为真的就全部过滤掉。