1

我有两个表,第一个表包含具有唯一 ID 和关键字的数字,第二个表包含通过唯一 ID 链接回第一个表的数字(在CAMPAIGN列中)。我想从第一个表中获取每个数字,并计算其唯一 ID(in 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
4

4 回答 4

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

这个查询将给出你所期望的......

于 2012-12-30T04:18:23.517 回答
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
于 2012-12-31T03:47:20.333 回答
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 子选择,这是你需要的。

于 2012-12-30T04:07:17.350 回答
0

作为您的问题的解决方案,请尝试执行以下 sql 查询

select c.number,keyword,(select count(id) as count from subscribers
where campaign=c.id) from  campaigns c 
于 2012-12-30T04:51:50.637 回答