mysql where OR having
I have a table of users, some of which have articles associated with them, and some of which have type = writer. I'd like to display all users who have articles OR who have type = writer. So, all writers should be displayed, and other user types are only displayed if they have articles.
This is my query so far, which开发者_开发知识库 leaves out writers with no articles.
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
Adding the following WHERE clause obviously excludes other user types that have articles.
WHERE u.type = 'writer'
Do I need to do a UNION of these two result sets?
I think you are looking for something like this
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.
Just change the WHERE clause to allow any user that has a matching article record:
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
精彩评论