mySQL count occurrences with JOIN

五迷三道 提交于 2020-02-23 08:08:20

问题


I have a tagging system for my events system I would like to create a 'tag cloud'.

I have Events, which can have multiple 'categories'.

Here's the table structure:

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

Summary:

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

I'd like to return the following:

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

other_tag - Not actually returned, as it has 0 occurrences

Thanks! :)


回答1:


this will work:

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

change the INNER JOIN to LEFT JOIN if you want to include categories with 0 occurances




回答2:


How about something like

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



来源:https://stackoverflow.com/questions/18101670/mysql-count-occurrences-with-join

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!