我有两张桌子:
表用户:
userId, user
------------
0, Alice
1, Bob
2, Eve
表 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
当我跑步时:
SELECT `users`.`user`, COUNT(*) FROM `rss` INNER JOIN `users` ON `rss`.`userId`=`users`.`userId` WHERE `rss`.`read`=0 GROUP BY `rss`.`userId`
我明白了:
Alice, 2
Bob, 1
但我想让夏娃提到(说明0),即
Alice, 2
Bob, 1
Eve, 0
答案 0 :(得分:3)
您需要外部联接:
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;
而且,我做了以下更改:
users
添加别名,以便查询更易于阅读和编写。left join
代替right join
。我认为left join
更容易阅读。group by
以使用users
表中的字段。rss
上的条件移至on
子句。