获取分组字段的计数,但也需要零计数的字段名称

时间:2015-07-06 15:16:11

标签: php mysql

你可能以前见过它。我正在尝试获取有多少短信消息属于文件夹的计数,但我仍然希望显示名为show up的字段不包含任何文件。

例如:

TABLE: inbox_compiled
message_text(text)
id_folder(int)     

TABLE: user_folders
id_folder(int)
name(text)

这是我使用的mysql语句:

SELECT 
user_folders.id_folder, name, COUNT(*) as msg_count 
FROM inbox_compiled, user_folders 
WHERE 
inbox_compiled.id_folder = user_folders.id_folder
GROUP BY name ORDER BY msg_count DESC


My results are this:
id_folder,name,msg_count
'1', 'inbox', '25'
'2', 'outbox', '1'

我应该(或想要)获得的是:)

id_folder,name,msg_count
'1', 'inbox', '25'
'2', 'outbox', '1'
'3', 'spam', '0'
'4', 'personal', '0'
'5', 'junk', '0'

(我知道表格字段不是最好的 - 这就是我现在正在使用的内容) 提前谢谢。

2 个答案:

答案 0 :(得分:1)

像这样的东西。

SELECT 
user_folders.id_folder, name, COUNT(inbox_compiled.id_folder) as msg_count 
FROM user_folders left join inbox_compiled on (inbox_compiled.id_folder = user_folders.id_folder)
GROUP BY name ORDER BY msg_count DESC;

答案 1 :(得分:0)

使用外连接,也不要使用count(*),只计算消息ID,例如

select f.id_folder, f.name, i.*, count(i.id) as msg_count from user_folders as f left join inbox_compiled as i on i.id_folder = f.id_folder group by f.name;