使用来自同一表的值更新MySQL表

时间:2021-07-12 17:08:31

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

我有一个4列的表,主键是id、gameId和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:

我需要更新表格,以便:

  • All of gameId 2 scores are added to gameId 1 where the id and flag is the same. (e.g. row 1 would have a score of 20 by adding the scores of row 1 and row 4)

    所有的gameId 2分数都被添加到gameId 1中,其中id和标志是相同的。(例如,第1行的分数加上第1行和第4行的分数,得到20分)

  • If the above happens the gameId 2 row needs to be deleted.

    如果发生上述情况,则需要删除gameId 2行。

  • Where the above isn't found (e.g. there is a row where the gameId is 2 but the id and flag don't match another row), the gameId can just be changed to 1.

    如果没有找到上面的内容(例如,有一行的gameId值为2,但id和标志不匹配另一行),则可以将gameId值更改为1。

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

所以SQL完成后,我的表应该是这样的:

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 :)

我如何用SQL写这个?谢谢:)

1 个解决方案

#1


4  

think this going to work:

认为这行得通:

Try 1

试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

试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;

#1


4  

think this going to work:

认为这行得通:

Try 1

试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

试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;