Mysql in count with left join and group by, how to make the result of count 0 display 0

SELECT COUNT(*)AS cnt FROM info AS i LEFT JOIN user AS u ON i.grpid=u.grpid WHERE i.type=1 GROUP BY i.grpid

the data with no results queried in this way will not be displayed. What can I do if I want the data without results to be displayed as 0?

Mar.30,2021

laxative, I don't see where your sql will be empty.
left link, where Filter left table field, groupby is also the left table, the record to which count
Filter is taken is sure count is not 0 either

then use ifnull (col1,0) to handle null values


I guess you need to change the join order of info and user


you can use MYSQL IF () Function

SELECT IF(SELECT COUNT(*)AS cnt FROM info AS i LEFT JOIN user AS u ON i.grpid=u.grpid WHERE i.type=1 GROUP BY i.grpid) = 0 , "0", SELECT COUNT(*)AS cnt FROM info AS i LEFT JOIN user AS u ON i.grpid=u.grpid WHERE i.type=1 GROUP BY i.grpid) AS cnt;

the following is the Syntax of IF

   IF(condition, value_if_true, value_if_false)

you can use mysql's if operation if you want the data with no result to be 0. Of course, it is recommended that it be done by the program.


use if to set a default value of 0 for the field you want it to be 0


The order of

is changed to from user first and then left join info table.
SELECT COUNT (i.id) AS cnt FROM user AS u LEFT JOIN info AS i ON i.grpid=u.grpid WHERE i.type=1 GROUP BY i.grpid

the reason is that info does not necessarily have records in the user table.
when querying, it will first find out all the records in the user table, and then find the total number of info records corresponding to the user.
according to the way you write it, if a user has no info record, there is nothing to display

MySQL Query : SELECT * FROM `codeshelper`.`v9_news` WHERE status=99 AND catid='6' ORDER BY rand() LIMIT 5
MySQL Error : Disk full (/tmp/#sql-temptable-64f5-1e50677-450b5.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
MySQL Errno : 1021
Message : Disk full (/tmp/#sql-temptable-64f5-1e50677-450b5.MAI); waiting for someone to free some space... (errno: 28 "No space left on device")
Need Help?