MySQL使用RIGHT JOIN获取项目数

时间:2013-12-12 20:09:39

标签: mysql sql count

我需要收集一位用户创建的所有帖子,并计算加入他们的人数。

我试过这个问题:

SELECT ads.id, ads.title, sign_ups.user_id
FROM sign_ups RIGHT JOIN ads ON ads.id = sign_ups.ad_id
WHERE advertiser_id=1

输出是:

id      title                  user_id
1      Something                  1
2      something else             2
3      another title             NULL
1      Something                  2

但我想:

id      title               total
1      Something              2
2      something else         1
3      another title          0

但我想:

id      title               total
1      Something              2
2      something else         1
3      another title          0

所以我试过这个:

SELECT ads.id, ads.title, count(sign_ups.user_id) AS total
FROM sign_ups
RIGHT JOIN ads ON ads.id = sign_ups.ad_id
WHERE advertiser_id =1

但是输出不包括没有跟随用户的所有title字段。所以结果如下:

id      title                  total
1      Something                 2
2      something else            1

想问一下,如何更改我的查询以获取所有想要的记录。

谢谢!

2 个答案:

答案 0 :(得分:1)

试试这个:

SELECT ads.id, ads.title, count(sign_ups.user_id) AS total
FROM sign_ups
RIGHT JOIN ads ON ads.id = sign_ups.ad_id
WHERE advertiser_id=1 AND sign_ups.user_id IS NOT NULL
UNION ALL
SELECT ads.id, ads.title, 0 AS total
FROM sign_ups
RIGHT JOIN ads ON ads.id = sign_ups.ad_id
WHERE advertiser_id=1 AND sign_ups.user_id IS NULL

答案 1 :(得分:0)

尝试使用“ifnull”,以确保即使那些没有用户ID的人也应该出现。我不确定这是不是你想要的,但我很乐意提供帮助。

SELECT ads.id, ads.title, ifnull(count(sign_ups.user_id), 0) AS total
FROM sign_ups
RIGHT JOIN ads ON ads.id = sign_ups.ad_id
WHERE advertiser_id =1

这是一篇关于IFNULL()的文章:http://dev.mysql.com/doc/refman/5.0/en/control-flow-functions.html#function_ifnull