如何通过交换两列值来更新MySQL表?

时间:2016-02-01 04:44:30

标签: mysql sql

我有三张桌子

CREATE TABLE guest(
name varchar(100),
ranking int,
PRIMARY KEY (name)
);

CREATE TABLE room(
roomname varchar(100),
wallcolor varchar(100),
rating int,
PRIMARY KEY(roomnane)
);

CREATE TABLE reservation(
name varchar(100),
roomname varchar(100),
day varchar(100),
moveinday int,
moveoutday int,
PRIMARY KEY(roomname, day, start, finish),
FOREIGN KEY(roomname) REFERENCES room(roomname),
FOREIGN KEY(name) REFERENCES guest(name)
);

我正在尝试将所有“湖泊”房间改为“海湾”房间和“海湾”房间改为“湖”房间,而没有明确更改所涉及的房间。我怎么能这样做?我尝试使用更新查询,但我不知道如何实现这一目标。

1 个答案:

答案 0 :(得分:4)

UPDATE room
SET roomname = (
    CASE
    WHEN roomname = "Bay" THEN
        "Lake"
    WHEN roomname = "Lake" THEN
        "Bay"
    ELSE
        roomname
    END
)

示例:

如果您的房间表在运行此查询之前如下所示:

enter image description here

然后在运行上述查询后,您的房间表看起来就像是保持其他房间不变:

enter image description here