mysql update multiple records of multiple tables using one statement based on condition

roozbeh S :

I have a mysql table for keeping record of two person competitions like this:

- 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

I need to check the records and update another table "users" based on the scores. ex: if score1 > score2 I need to update 3 things:

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

So far I am able to update 1 and 2 but I need all the 3 updates in one command:

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

I can separate the +1 and -1 commands, it will work fine. But when the command is run, both users' scores should be updated. Can anyone help?

GMB :

This should do it:

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)

The logic is to select two rows in the user table, and then do conditional logic to decide whether to add or remove a point.

Note: you did not tell how you want to handle tied competitions - so this query explicitly ignores them.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=31838&siteId=1