David Normington
David Normington

Reputation: 847

MySQL update table with values from same table

I have a 4 column table, the primary key is a composite of id, gameId and flag.

id | gameId | score | flag
--------------------------
1  | 1      | 10    | 1
1  | 1      | 20    | 0
2  | 1      | 1     | 0
1  | 2      | 10    | 1
3  | 2      | 1     | 0

I need to update the table so that:

So my table after the SQL is complete should look like this:

id | gameId | score | flag
--------------------------
1  | 1      | 20    | 1
1  | 1      | 20    | 0
2  | 1      | 1     | 0
3  | 1      | 1     | 0

How can I write this in SQL? Thanks :)

Upvotes: 4

Views: 7511

Answers (1)

Puggan Se
Puggan Se

Reputation: 5846

think this going to work:

Try 1

UPDATE score_list AS t2
LEFT JOIN score_list AS t1 ON
  (t1.id = t2.id AND t1.flag = t2.flag AND t1.gameId = 1)
SET
  t1.score = t1.score + t2.score,
  t2.gameId = IF(t1.gameId IS NULL, 1, t2.gameId)
WHERE t2.gameId = 2;

DELETE FROM score_list WHERE gameId = 2;

Try 2

# add scores to gameId = 1
UPDATE score_list AS t2
LEFT JOIN score_list AS t1 ON
  (t1.id = t2.id AND t1.flag = t2.flag AND t1.gameId = 1)
SET
  t1.score = t1.score + t2.score
WHERE t2.gameId = 2;

# try to move gameID 2 to gameId 1, using ignore to allow rows to fail, as gameId alredy exists
UPDATE IGNORE score_list SET gameId = 1 WHERE gameId = 2;

# delete all not updated rows from last query
DELETE FROM score_list WHERE gameId = 2;

Upvotes: 6

Related Questions