Let's say I have two tables:
+------------------------------------+
| `houses` |
+----+-------+-------+-------+-------+
| id | house | room1 | room2 | room3 |
+----+-------+-------+-------+-------+
| 1 | a | 1 | 1 | 2 |
| 2 | b | 1 | 3 | 1 |
| 3 | c | 2 | 2 | 1 |
+----+-------+-------+-------+-------+
+------------------------+
| `status` |
+-------------+----------+
| status_code | status |
+-------------+----------+
| 1 | empty |
| 2 | occupied |
| 3 | full |
+-------------+----------+
Now I want to change room1, room2 and room3's ids to the status from TABLE status
like this:
+---------------------------------------------+
| `houses` |
+----+-------+----------+----------+----------+
| id | house | room1 | room2 | room3 |
+----+-------+----------+----------+----------+
| 1 | a | empty | empty | occupied |
| 2 | b | empty | full | empty |
| 3 | c | occupied | occupied | empty |
+----+-------+----------+----------+----------+
I know one solution, but I believe there is an easier way to do the same:
SELECT
h.*,
s1.status AS room1,
s2.status AS room2,
s3.status AS room3
FROM houses h
JOIN status s1 ON h.room1 = s1.status_code
JOIN status s2 ON h.room2 = s2.status_code
JOIN status s3 ON h.room3 = s3.status_code
UPDATE
MySQL pivot table solution is not suitable for me because the above example is a simplified version what I use. There are more than ten different status and writing a 40 line CASE function for a single room is not an opportunity. The status
must come from the status table.