开发者

MySQL Left Join + Where problem

开发者 https://www.devze.com 2023-02-10 05:56 出处:网络
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 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 d开发者_如何转开发o. 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.

0

精彩评论

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

关注公众号