2013-10-31 20 views
0

我在試圖找出這個問題時遇到了麻煩。我有這3個表格:標籤列表,文章列表,關係列表。文章在每個標籤中出現多少次?

他們去如下:

標籤

id | name 
----------- 
1 | tag1 
2 | tag2 
3 | tag3 
4 | noArticles 

文章

id | title | active 
------------------------ 
1 | product1 | 1 
2 | product2 | 1 
3 | product3 | 0 
4 | product4 | 1 
5 | product5 | 0 
6 | product6 | 1 

關係

article_id | tag_id 
--------------------- 
    1  | 1 
    1  | 3 
    2  | 3 
    3  | 1 
    3  | 2 
    4  | 2 
    4  | 3 
    5  | 2 
    6  | 1 
    6  | 2 
    6  | 1 

我知道一篇文章只能有一個標籤。那麼,我想要的查詢是這樣的:

第N條(讓說... 4)出現在每個標籤有多少活躍的文章?

答案會是這樣的:

name | times 
-------------- 
tag1 | 0  
tag2 | 1  
tag3 | 1  

我會確保在文章中,我搜索是積極的事前。

+0

確定。修復。 ;) – hbmuller

+1

啊!我會顯示答案。等一下。 – hbmuller

+0

+1現在很清楚你在找什麼 –

回答

1

對您的問題編輯後,它現在很清楚,你在找什麼:

SELECT t.name, SUM(r.article_id = 4) times FROM tags t 
LEFT JOIN relations r ON r.tag_id = t.id 
JOIN articles a ON r.article_id = a.id 
WHERE a.active = 1 
GROUP BY t.id 

小提琴here

我想你已經知道,在4存在article N :)

+1

是的,就是這樣。非常感謝! – hbmuller

-1

試了這句話,但我很好地工作:

SELECT 
    `Tags`.`name`, 
    `Articles`.`active`, 
    COUNT(`Relations`.`Tags_id`) AS `count` 
    FROM  `Relations`,`Articles`,`Tags` 

    WHERE 
      `Articles`.`id` = `Relations`.`article_id` 
     AND `Tags`.`id` = `Relations`.`tag_id` 

    GROUP BY `Relations`.`article_id` 
+1

謝謝,夥計。但實際上我想看到**所有標籤都有活動文章**,並且如果特定文章**有或沒有**每個標籤。 – hbmuller

+0

好的,我做了改變,批准我的答案:P – Troncador