mysql在哪里OR

时间:2011-04-26 15:37:54

标签: mysql sql count left-join where

我有一个用户表,其中一些有与之关联的文章,其中一些有type = writer。我想显示所有有文章或者有type = writer的用户。因此,应显示所有作者,并且只有在有文章的情况下才会显示其他用户类型。

到目前为止,这是我的查询,这使作家没有文章。

SELECT u.name, u.type, COUNT(a.id) count
FROM users u
LEFT JOIN articles a on u.id = a.writer_id
GROUP BY u.name
HAVING count > 0

添加以下WHERE子句显然会排除其他具有文章的用户类型。

WHERE u.type = 'writer'

我是否需要对这两个结果集进行UNION?

2 个答案:

答案 0 :(得分:4)

我认为你正在寻找像这样的东西

SELECT 
  u.name, 
  u.type, 
  COUNT(a.id) count
FROM users u
LEFT JOIN articles a ON u.id = a.writer_id
WHERE 
  u.type='writer' --all users that are writers
  OR 
  a.writer_id IS NOT NULL  --all users that have at least one article
GROUP BY 
  u.name
--removed the having clause as it seems it may be possible that a writer has no articles.

答案 1 :(得分:2)

只需更改WHERE子句以允许任何具有匹配文章记录的用户:

SELECT u.name, u.type, COUNT(a.id) count
FROM users u
LEFT JOIN articles a on u.id = a.writer_id
WHERE u.type = 'writer' OR a.writer_id IS NOT NULL
GROUP BY u.name
HAVING count > 0