我需要收集一位用户创建的所有帖子并获取加入这些帖子的人数。
我尝试过这个查询:
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
想问一下,如何更改我的查询以获取所有想要的记录。
谢谢!
最佳答案
试试这个:
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
关于MySQL 使用 RIGHT JOIN 获取项目计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20553237/