我有两个表,第一个表包含具有唯一ID和关键字的数字,第二个表包含通过唯一ID(在CAMPAIGN
列中)链接回第一个表的数字。我想从第一个表中获取每个数字并计算其唯一ID(在CAMPAIGN
中)在第二个表中显示的次数(即:每个数字附加了多少个关键字)。
CAMPAIGNS SUBSCRIBERS
---------------------------------- --------------------------------------
ID | NUMBER | KEYWORD | | ID | NUMBER | CAMPAIGN |
---------------------------------- --------------------------------------
1 | +1222222222 | pizza | | 22 | 555-333-222 | 2 |
---------------------------------- --------------------------------------
2 | +1222222222 | burger | | 21 | 222-333-222 | 2 |
---------------------------------- --------------------------------------
3 | +1444444444 | pie | | 33 | 333-111-111 | 1 |
----------------------------------
4 | +1111111111 | chicken |
我需要的结果是:
----------------------------------------
NUMBER | KEYWORD | COUNT |
----------------------------------------
+1222222222 | pizza | 1 |
----------------------------------------
+1222222222 | burger | 2 |
----------------------------------------
+1444444444 | pie | 0 |
----------------------------------------
+1111111111 | chicken | 0 |
我对JOIN
和UNION
不太熟悉,所以我一直在试验和阅读文档,但我无法弄清楚如何用它们实现COUNT
。
这是我到目前为止所做的,但每当我尝试添加COUNT
函数时,我都会收到错误而无法弄明白:
SELECT * FROM `campaigns` LEFT JOIN `subscribers` ON `campaigns`.id = `subscribers`.campaign;
修改 发布的查询类型有效,但不包括计数为零的其他广告系列
SELECT c.number,c.id,c.keyword,COUNT(s.id) AS count FROM campaigns AS c LEFT JOIN subscribers AS s ON c.id = s.campaign GROUP BY s.campaign ORDER BY c.id ASC
答案 0 :(得分:1)
SELECT c.number,c.keyword,COUNT(s.campaign)
FROM `campaigns` AS c
LEFT JOIN `subscribers` AS s ON c.id = s.campaign
GROUP BY c.id
ORDER BY c.id ASC
此查询将提供您期望的内容......
答案 1 :(得分:1)
SELECT c.number, c.id, c.keyword, ISNULL(s.count,0) AS count
FROM campaigns AS c
LEFT JOIN (
SELECT Campaign, COUNT(*) AS count
FROM Subscribers
GROUP BY Campaign
) AS s
ON c.id = s.Campaign
ORDER BY c.id ASC
答案 2 :(得分:0)
SELECT campaigns.number AS number, campaigns.keyword AS keyword, COUNT( subscribers.id ) AS count
FROM `subscribers`
LEFT JOIN `campaigns` ON subscribers.campaign = campaigns.id
GROUP BY campaigns.keyword
是你需要的。唯一不起作用的是显示带有0个订阅者的“馅饼”...我很遗憾没有进入mysql子选择,这就是你需要的。
答案 3 :(得分:0)
作为您问题的解决方案,请尝试执行以下sql查询
select c.number,keyword,(select count(id) as count from subscribers
where campaign=c.id) from campaigns c