如何用值替换参考ID

时间:2019-06-25 09:38:28

标签: mysql

假设我有两个表:

+------------------------------------+
|              `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     |
+-------------+----------+

现在,我要像这样将room1,room2和room3的ID从TABLE status更改为状态:

+---------------------------------------------+
|                   `houses`                  |
+----+-------+----------+----------+----------+
| id | house |  room1   |  room2   |  room3   |
+----+-------+----------+----------+----------+
|  1 | a     | empty    | empty    | occupied |
|  2 | b     | empty    | full     | empty    |
|  3 | c     | occupied | occupied | empty    |
+----+-------+----------+----------+----------+

我知道一个解决方案,但是我相信有一种更简单的方法可以做到这一点:

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

更新

MySQL pivot table解决方案不适合我,因为上面的示例是我使用的简化版本。有十多个不同的状态,为单个房间编写40行CASE功能不是一个机会。 status必须来自状态表。

1 个答案:

答案 0 :(得分:0)

您可以采用

SELECT id,house,
(
  CASE
    WHEN room1 > 0 THEN (SELECT status FROM status WHERE status_code=room1)
 END) AS room1,
(
  CASE
    WHEN room2 > 0 THEN (SELECT status FROM status WHERE status_code=room2)
 END) AS room2,
(
  CASE
    WHEN room3 > 0 THEN (SELECT status FROM status WHERE status_code=room3)
 END) AS room3
 FROM houses

Live DEMO