开发者

trying to join two tables and get the count of how many comments were made about a department

My sql is not working when trying to get the total number of comments that were made by each department.

select * from departments d
  COUNT( comments.department_id ) AS total_comments
FROM
  d
LEFT JOIN
  comments c
ON
  ( d.id = c.department_id )
GROUP BY
  d.id, d.title

comments.department_id = departments.id

UPDATE: I neglected to mention I want to display the results in this manner: departments.title (total_comments)

Example: Maintenance (4)

SOLVED: needed to group it by d.t开发者_如何转开发itle as well, now GROUP BY is d.id, d.title


SELECT departmentID, COUNT(*)
FROM COMMENTS
GROUP BY departmentID

if you need departments that have no comments:

SELECT d.DepartmentID, Count(c.DepartmentID)
FROM Departments d
LEFT JOIN Comments c on d.departmentid = c.departmentid
GROUP BY d.DepartmentID
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜