So, I have a MySQL table that is similar this one:
|Day | Participant| Score |
+----+------------+-------+
|Mon | Andy | 9 |
|Mon | Betty | 8 |
|Mon | Charlie | 7 |
|Tue | Andy | 6 |
|Tue | Betty | 6 |
|Tue | Charlie | 8 |
|Wed | Andy | 7 |
|Wed | Charlie | 4 |
I want to output it into this:
| Day | Andy | Betty | Charlie |
+-----+------+-------+---------+
| Mon | 9 | 8 | 7 |
| Tue | 6 | 6 | 7 |
| Wed | 7 | null | 4 |
I approached this problem with PHP and this is what I came up with:
- Query the names of each participant.
With PHP, build a sub-query for each participant's score in each day, like this one:
SELECT score FROM TableName WHERE (Day=ref_point AND Participant='Andy')
Generate the main query, with all the sub-queries included, like this:
SELECT Day AS ref_point,(/* Sub-query for Andy */) AS Andy,(/* Sub-query for Betty */) AS Betty,(/*Sub-queries for the rest of participants */) AS Others FROM TableName GROUP BY Day
This works quite fine, but as the number of participants grow, so does the query string. I fear that one day the query become longer than PHP's max string length. I need to know how to do this entirely in MySQL.