Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL Left Join + Where problem

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!

like image 677
Charles Avatar asked Dec 29 '22 01:12

Charles


1 Answers

Since you are using a LEFT JOIN, move the a.status = 'assigned' predicate from the WHERE clause to the JOIN clause.

SELECT u.name, COUNT(a.id) as count 
FROM users u LEFT OUTER JOIN articles a 
  ON a.writer_id = u.id
  AND a.status = 'assigned' 
WHERE u.type = 'writer' 
GROUP BY u.name

Explanation: For those users that do not have a article a.status will be NULL, Leaving the predicate in the WHERE defeats the purpose of a LEFT join, since NULL = 'assigned' will evaluate to false.

like image 157
The Scrum Meister Avatar answered Jan 13 '23 21:01

The Scrum Meister