且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

MYSQL:COUNT与GROUP BY,LEFT JOIN和WHERE子句不返回零值

更新时间:2022-11-30 17:45:54

它返回零行的原因是您正在对table_1中的值进行分组.由于table_1中没有值,因此没有要返回的行.换句话说,如果您从GROUP BY中返回查询中的t1.any_col,如下所示:

The reason it returns zero rows is that you are grouping on a value in table_1. SInce there are no values in table_1, there are no rows to return. Said another way, if you returned t1.any_col in your query from the GROUP BY like so:

SELECT `t1`.`any_col`, COUNT(`t2`.`name`) 
FROM `table_1` `t1` 
    LEFT JOIN `table_2` `t2` ON `t1`.`key_id` = `t2`.`key_id` 
WHERE `t1`.`another_column` = 123 
GROUP BY `t1`.`any_col` 

在没有行的情况下,t1.any_col将显示什么?实现所需目标的唯一方法是将结果与另一个检查table_1中没有行的查询合并.在此示例中,我仅使用INFORMATION_SCHEMA视图来查询某些内容.

What would display for t1.any_col when there were no rows? The only way to achieve what you want is to union your results with another query that checks for no rows in table_1. In this example, I'm using the INFORMATION_SCHEMA view simply to have something against which I can query.

SELECT COUNT(`t2`.`name`) 
FROM `table_1` `t1` 
    LEFT JOIN `table_2` `t2` ON `t1`.`key_id` = `t2`.`key_id` 
WHERE `t1`.`another_column` = 123 
GROUP BY `t1`.`any_col` 
UNION ALL
SELECT 0
FROM INFORMATION_SCHEMA.TABLES
Where Not Exists( Select 1 From `table_1` )
LIMIT 1