简体   繁体   中英

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!

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM