2012-12-30 48 views
1

我有兩個表,第一個表包含帶唯一ID和關鍵字的數字,第二個表包含通過唯一ID鏈接回第一個表的數字(在CAMPAIGN列中)。我想從第一個表格中獲得每個數字,並計算他們的唯一ID(在CAMPAIGN中)在第二個表格中顯示的次數(即:每個數字附加了多少個關鍵字)。從第一個表中選擇全部,在第二個表中計數ID實例

  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 | 

我不是太熟悉JOINUNION所以我一直在嘗試通過實況的閱讀,但我不能完全弄清楚如何實施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

從理論上講,你需要一個小組在最後 – Skynet

回答

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 
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個用戶顯示「pie」...我很遺憾不能進入你需要的mysql子選項。

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

這很好。快速提問。是'FROM campaigns c'與'FROM campaigns AS c'相同。有點困惑那裏。 – cantaffordretail

+0

嗯,有一個問題 - 它只顯示第一個有0個結果的值,如果它們有0個結果,則不顯示任何額外的'Campaign.id'。 – cantaffordretail

+0

我已經更新了上面的帖子中的查詢,請現在檢查... –

0

至於你的問題的解決方案請嘗試以下SQL查詢執行

select c.number,keyword,(select count(id) as count from subscribers 
where campaign=c.id) from campaigns c 
+0

此查詢不包括有0的結果(即:關鍵字'pie') – cantaffordretail

相關問題