Eu usaria
insert .. on duplicate key update ...
declaração. Algo assim:insert into highscore set
name = :name,
score = :new_score
on duplicate key update
score = greatest(score, :new_score)
name
coluna deve ser indexada como unique
. Roteiro de teste:
create table player (
name varchar(32) primary key,
score int not null default 0
);
-- create new players
insert into player set name = 'foo', score = 100
on duplicate key update score = greatest(score, 100);
insert into player set name = 'bar', score = 100
on duplicate key update score = greatest(score, 100);
insert into player set name = 'baz', score = 100
on duplicate key update score = greatest(score, 100);
-- update score of existing player
insert into player set name = 'bar', score = 200
on duplicate key update score = greatest(score, 200);
Saída de
select * from player
:+------+-------+
| name | score |
+------+-------+
| bar | 200 |
| baz | 100 |
| foo | 100 |
+------+-------+