mysql – 在同一查询中访问先前更新的列的行为与JOIN /多表UPDATE的行为不同

假设我有两个表玩家和统计数据,其中包含以下内容:

mysql> select * from players;
+----+-------+
| id | alive |
+----+-------+
|  1 |     0 |
|  2 |     1 |
+----+-------+
mysql> select * from stats;
+--------+------+------+-------+
| player | win  | lose | ratio |
+--------+------+------+-------+
|      1 |   12 |   20 |   0.6 |
|      2 |    8 |    1 |     8 |
+--------+------+------+-------+

而且我想增加每个玩家的胜利计数器,同时还要更新他们的赢/输比率.这看起来像这样:

update `stats` set `win` = `win` + 1, `ratio` = `win` / `lose`;

请注意,增加的win值用于计算比率(正如mysql的手册中所述:1.8.2.2 UPDATE Differences).

现在,当一个JOIN添加到UPDATE查询以限制它仅更新alive = 1的播放器时,此行为会更改:

update `stats` st
inner join `players` pl
    on ( pl.`id` = st.`player` )
set `win` = `win` + 1, `ratio` = `win` / `lose`
where pl.`alive` = 1;

mysql> select * from stats;
+--------+------+------+-------+
| player | win  | lose | ratio |
+--------+------+------+-------+
|      1 |   12 |   20 |   0.6 |
|      2 |    9 |    1 |     8 |
+--------+------+------+-------+

我发现的唯一解决方案是将win的新值分配给临时变量,并在计算比率时使用该值:

update `stats` st
inner join `players` pl
    on ( pl.`id` = st.`player` )
set
    `win` = @tmpWin := ( `win` + 1 ),
    `ratio` = @tmpWin / `lose`
where pl.`alive` = 1;

为什么MySQL表现得那样,是否有更优雅的解决方案解决这类问题(除了创建一个视图来动态计算比率)?

表格创建如下:

create table `players` (
    `id`        INT,
    `alive`     TINYINT,
    primary key (`id`)
);

create table `stats` (
    `player`    INT,
    `win`       INT,
    `lose`      INT,
    `ratio`     FLOAT,
    primary key (`player`)
);

我正在使用MySQL v5.7.17

最佳答案 我无法解释连接案例的行为确实看起来很奇怪,但以下工作符合预期:

 UPDATE `stats` 
 SET `win` = `win` + 1, `ratio` = `win` / `lose` 
 WHERE player IN (SELECT id FROM players WHERE alive=1);
点赞