BigDistance
BigDistance

Reputation: 135

mySQL count occurrences with JOIN

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! :)

Upvotes: 1

Views: 3414

Answers (2)

x4rf41
x4rf41

Reputation: 5337

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

Upvotes: 6

Adriaan Stander
Adriaan Stander

Reputation: 166376

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

Upvotes: 2

Related Questions