Chip
Chip

Reputation: 131

MySQL: Performance Querying Multiple Columns With a Single Row

My tables simplified something like this..

Table Categories
cat_id   | cat_name
-------------------
1        | Baseball
2        | Hockey
3        | Football

Table Day
day_id   | day_name
--------------------
1        | Friday
2        | Saturday
3        | Sunday

Table Day_Categories
day_id    | cat_id
-------------------
1         | 1
1         | 2
2         | 2
2         | 3
3         | 1
3         | 2
3         | 3

And I want my resulting data to look something like this...

"Friday","Baseball, Hockey"
"Saturday","Hockey, Football"
"Sunday", "Baseball, Hockey, Football"

It doesn't necessary need to be in three row format. I just need the same resulting data.

From a performance prospective with lots of data what's likely the best way to achieve this result?

Upvotes: 0

Views: 134

Answers (1)

Savas Vedova
Savas Vedova

Reputation: 5692

Please try this one

SELECT day_name, GROUP_CONCAT ( cat_name ) as categories 
FROM Days as d
LEFT JOIN Days_Categories as dnc ON d.day_id = dnc.day_id 
LEFT JOIN Categories as c ON c.cat_id = dnc.cat_id 
GROUP BY ( dnc.day_id)

Upvotes: 3

Related Questions