需要从mysql返回每个部门的标题和计数

时间:2011-10-14 19:40:10

标签: mysql sql

表:

departments: id, title

comments: id, year_code

department_comments: comment_id, department_id

我想列出每个部门的标题,以及它有多少评论的数量。

的内容
select 
 d.title, count(c.id) as total_comments
from 
 departments d, comments c
left join
 department_comments dc on c.id = dc.comment_id 
where
 c.year_code = 1011

上述查询不起作用,但应该让您知道我想要完成的任务。

我想要向用户显示的是部门标题和旁边的评论总数,如下所示:

d.title (count(c.id))
---------------------
Maintenance (10)
Finance (5)
Security (13)

1 个答案:

答案 0 :(得分:4)

你很亲密。你的JOIN语法有点偏,你错过了GROUP BY。

SELECT d.title, COUNT(dc.comment_id) AS total_comments
    FROM departments d
        LEFT JOIN department_commments dc
            INNER JOIN comments c
                ON dc.commment_id = c.id
                    AND c.year_code = 1011
            ON d.id = dc.department_id
    GROUP BY d.title