0

I have two tables:

Table users:

userId, user
------------
0, Alice
1, Bob
2, Eve

Table rss:

userId, link, read
------------
0, example.com/1, 0
0, example.com/2, 1
0, example.com/3, 1
0, example.com/4, 0
1, example.com/3, 0
1, example.com/4, 1

When I run:

SELECT `users`.`user`, COUNT(*) FROM `rss` INNER JOIN `users` ON `rss`.`userId`=`users`.`userId` WHERE `rss`.`read`=0 GROUP BY `rss`.`userId`

I get:

Alice, 2
Bob, 1

But I would like to also have Eve mentioned (stating 0), i.e.,

Alice, 2
Bob, 1
Eve, 0

1 Answer 1

3

You need an outer join:

SELECT u.`user`, COUNT(rss.userId)
FROM users u LEFT JOIN
     rss
     ON rss.userId = u.userId AND rss.`read` = 0
GROUP BY u.userId;

And, I made the following changes:

  • Add alias for users so the query is easier to read and write.
  • Switched the tables so I could use left join instead of right join. I think left join is easier to read.
  • Changed the group by to use the field from the users table.
  • Moved the condition on rss to the on clause.
  • Removed most of the back ticks. They just clutter the query.
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.