使用JOIN进行mySQL计数

时间:2013-08-07 11:01:06

标签: mysql join count one-to-many

我的事件系统有一个标记系统我想创建一个'标签云'。

我有活动,可以有多个'类别'。

这是表结构:

**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           |   

要点:

Event ID 1 -> Sport
Event ID 2 -> Charity
Event ID 3 -> Sport, Charity

我想退回以下内容:

| tag_name  | occurrences |
+-----------+-------------+
|  sport    |     2       |
|  society  |     2       |

other_tag - 实际上没有返回,因为它有0次出现

谢谢! :)

2 个答案:

答案 0 :(得分:4)

这将有效:

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 
GROUP BY c.id
如果您想要包含0次出现的类别,请

INNER JOIN更改为LEFT JOIN

答案 1 :(得分:2)

这样的东西
SELECT e.name,
COUNT(1)
FROM Event_Categories e INNER JOIN
Events_Categories_Linking ec ON e.id = ec.event_category_id
GROUP BY e.name

SQL Fiddle DEMO