例如:
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'
(我知道表格字段不是最好的 - 这就是我现在正在使用的内容) 提前谢谢。
答案 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;