1

我的事件系统有一个标记系统,我想创建一个“标记云”。

我有事件,它可以有多个“类别”。

这是表结构:

**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 次出现

谢谢!:)

4

2 回答 2

5

这将起作用:

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 JOINLEFT JOIN

于 2013-08-07T11:04:23.410 回答
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 小提琴演示

于 2013-08-07T11:06:33.973 回答