Mysql
 sql >> Database >  >> RDS >> Mysql

MYSQL:COUNT con la clausola GROUP BY, LEFT JOIN e WHERE non restituisce zero valori

Il motivo per cui restituisce zero righe è che stai raggruppando su un valore in table_1. Poiché non ci sono valori in table_1, non ci sono righe da restituire. Detto in un altro modo, se hai restituito t1.any_col nella tua query da GROUP BY in questo modo:

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` 

Cosa verrebbe visualizzato per t1.any_col quando non c'erano righe? L'unico modo per ottenere ciò che desideri è unire i risultati con un'altra query che non verifica la presenza di righe nella tabella_1. In questo esempio, sto usando la vista INFORMATION_SCHEMA semplicemente per avere qualcosa su cui posso interrogare.

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