【问题标题】:mysql update multiple records of multiple tables using one statement based on conditionmysql根据条件使用一条语句更新多张​​表的多条记录
【发布时间】:2020-06-19 16:05:55
【问题描述】:

我有一个 mysql 表来记录这样的两个人的比赛:

- gameid
- id1 // id of player 1
- id2 // id of player 2
- score1 // score of player 1
- score2 // score of player 2
- state // state of the games is initially 0, then the score updates are made and in order to prevent further updates the state must be updated to 1

我需要检查记录并根据分数更新另一个表“用户”。前任: 如果 score1 > score2 我需要更新 3 件事:

1- the state of the game // from 0 to 1
2- in table "users" add 1 point to the column score for the user with userid = id1
2- in table "users" subtract 1 point from the column score for the user with userid = id2

到目前为止,我可以更新 1 和 2,但我需要在一个命令中完成所有 3 个更新:

UPDATE dbo.games AS GA , dbo.users AS US 
SET GA.state = 1, US.score = US.score + 1
WHERE US.id = GA.id1 AND GA.state = 0 and GA.score1 > GA.score2

我可以将 +1-1 命令分开,它可以正常工作。但是当命令运行时,两个用户的分数都应该更新。有人可以帮忙吗?

【问题讨论】:

  • 你能写一个返回等效结果的SELECT吗?
  • 并确认您的 RDBMS

标签: mysql sql join sql-update


【解决方案1】:
UPDATE dbo.games AS GA , dbo.users AS US     
SET GA.state = 1, (CASE WHEN US.id =GA.id1 THEN US.score = US.score + 1
 ELSE WHEN US.id=id2 THEN US.score =US.score-1 END)  
WHERE  GA.state = 0 and GA.score1 > GA.score2

此查询在 US.id=id1 时将分数增加 1,当 US.id =id2 时将分数减少 1

【讨论】:

    【解决方案2】:

    应该这样做:

    update dbo.games as ga, dbo.users as us
    set 
        ga.state = 1, 
        us1.score = us1.score + case 
            when 
                (ga.score1 > ga.score2 and us.id = ga1.id1)
                or (ga.score2 > ga.score1 and us.id = ga2.id2)
            then 1
            else -1
        end
    where 
        ga.state = 0 
        and ga.score1 <> ga.score2
        and us.id in (ga.id1, ga.id2)
    

    逻辑是在用户表中选择两行,然后做条件逻辑来决定是否添加或删除一个点。

    注意:您没有说明要如何处理平局比赛 - 因此此查询明确忽略它们。

    【讨论】:

    • 谢谢,我得到了错误:#1690 - BIGINT UNSIGNED value is out of range,但是如果我把 -1 改成 0 就可以了。
    • 我将行更改为 ELSE(当 us.score >= 1 然后 -1 ELSE 0 END 时的情况),一切都像一个魅力。谢谢。