I have two mySQL tables in my database
Training:
+-------------+------------+------------+------------+-...-+------------+
| Training_ID | 09-06-2012 | 16-06-2012 | 23-06-2012 | ... | 28-12-2013 |
+-------------+------------+------------+------------+-...-+------------+
| 1 | 123 | 924 | 367 | | 679 |
+-------------+------------+------------+------------+-...-+------------+
| 2 | 243 | 626 | 381 | | 771 |
+-------------+------------+------------+------------+-...-+------------+
| 3 | 766 | 826 | 956 | | 725 |
+-------------+------------+------------+------------+-...-+------------+
Users:
+---------+----------+
| User_ID | Name |
+---------+----------+
| 123 | Fred |
+---------+----------+
| 924 | James |
+---------+----------+
| 367 | Tim |
+---------+----------+
| 766 | Mark |
+---------+----------+
What I want to show is:
+-------------+------------+-------------+------------+-...-+------------+
| Training_ID | 09-06-2012 | 16-06-2012 | 23-06-2012 | ... | 28-12-2013 |
+-------------+------------+-------------+------------+-...-+------------+
| 1 | 123 - Fred | 924 - James | 367 - Tim | | 679 - Ben |
+-------------+------------+-------------+------------+-...-+------------+
| 2 | 243 - Sarah| 626 - Smith | 381 - Exam | | 771 - John |
+-------------+------------+-------------+------------+-...-+------------+
| 3 | 766 - Mark | 826 - Jone | 956 - Case | | 725 - Brett|
+-------------+------------+-------------+------------+-...-+------------+
Note: there are actually 70 columns (all the same format as the above).
I tried using joins – but I cant do one for each column.
Is there a way to apply a join to the whole table?
That looks like a terrible design and any query you’re going to perform to produce your desired format will also look equally as horrid, but it isn’t impossible:
What you can do is make a single Cartesian-join of the
traininganduserstable, thenGROUP BYthetraining_id, and make a bunch of conditional aggregations which will put everything on one row pertraining_id:You’ll need as many
MAX(CASE WHEN… columns in yourSELECTclause as there are columns in your table.While this may also look ugly, it is much more efficient than joining the
userstable 70 different times for each column.SQLFiddle Demo with just four columns