开发者

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

开发者 https://www.devze.com 2023-01-31 11:50 出处:网络
My sql is not working when trying to get the total number of comments that were made by each 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

精彩评论

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