条件に基づいて1文を使用して複数のテーブルの複数のレコードを更新するのMySQL

S roozbeh:

私はこのような2つの競技の記録を維持するための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それがうまく動作しますが、コマンドを。コマンドが実行されたときしかし、両方のユーザのスコアが更新されるべきです。誰の助けができますか?

GMB:

これはそれを行う必要があります。

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)

ロジックは、選択することで2つの行をユーザテーブルに、その後、ポイントを追加または削除するかどうかを決定するために、条件付きロジックを実行します。

注:あなたが結ば競技を処理する方法を教えてくれませんでした - ので、このクエリでは、明示的に無視します。

おすすめ

転載: http://43.154.161.224:23101/article/api/json?id=32309&siteId=1