I have a table of Users: id, type, name
and a table of Articles: id, writer_id, status
where articles.writer_id = users.id.
I’d like to display a table of each User’s name WHERE type = ‘writer’ along with how many Articles are associated with them that have status = ‘assigned’.
So far I have:
SELECT u.name, COUNT(a.id) as count
FROM users u LEFT OUTER JOIN articles a
ON a.writer_id = u.id
WHERE u.type = 'writer' AND a.status = 'assigned'
GROUP BY u.name
Problem is, this doesn’t display writers with 0 ‘assigned’-status articles associated with them. I’m pretty sure I need a subquery but I’m not sure what to do. Thanks in advance!
Since you are using a
LEFT JOIN, move thea.status = 'assigned'predicate from the WHERE clause to the JOIN clause.Explanation: For those users that do not have a article
a.statuswill beNULL, Leaving the predicate in the WHERE defeats the purpose of a LEFT join, sinceNULL = 'assigned'will evaluate to false.