2013-08-07 48 views
-2

我在這裏問一個問題:mySQL count occurrences with JOINMySQL的計數出現與JOIN(與日期參數)

這個問題,詢問如何加盟後等數標籤的出現

我想知道如何要做到這一點,而且還要檢查事件publish_date,因爲我只想在過去6個月或一年中添加標籤。

**events** 
| id | publish_date | 
+-------------------------+ 
+ 1 | 1377612000  | 
+ 2 | 1377612000  | 
+ 3 | 1377612000  | 

**Event_Categories** (Stores Tags/Categories) 
| id | name  | 
+-----------------+ 
+ 1 | sport  | 
+ 2 | charity | 
+ 3 | other_tag | 


**Events_Categories** (Linking Table) 
| event_id | event_category_id | 
+-------------------------------+ 
+ 1  |  1   | 
+ 2  |  2   | 
+ 3  |  1   | 
+ 3  |  2   | 

SQL返回的標籤(不考慮發佈日期)SELECT c.name算作

tag_name, COUNT(ec.event_id) AS occurrences 
FROM Event_Categories c 
INNER JOIN Events_Categories ec ON c.id = ec.event_category_id 
GROUP BY c.id 

謝謝! :)

+1

我看不到publish_date並沒有付出您的努力。 –

+0

publish_date將位於events_Categories鏈接的events表上,該表顯示了event_id。我認爲沒有必要顯示事件表,因爲只有相關的字段是id&publish_date(unix時間) – BigDistance

+0

@juergend - 對不起,你有這種感覺,我在這裏問過,並認爲我提供了所有的信息。在問這個問題的同時,我一直在嘗試自己的解決方案(見下文) – BigDistance

回答

0
SELECT c.name AS tag_name, COUNT(ec.event_id) AS occurrences 
FROM event_categories c 
INNER JOIN events_categories ec ON c.id = ec.event_category_id 
JOIN events e ON e.id = ec.event_id 
WHERE(e.publish_end_date > (unix_timestamp() -7889229) OR e.publish_end_date = 0) 
GROUP BY c.id