MSQL:如果新条目更高,如何覆盖条目?否则创建新条目

0 php mysql flash

我有这样名为"highscore"的表:
nameQL scoreQL
piotr 50

与NAME和SCORE一起使用此名称导出到PHP的Flash游戏.

如何在PHP文件中创建:

  • IF(NAME存在于数据库(nameQL)和SCORE> this.name.scoreQL){Raplace scoreQL with SCORE WHERE nameQL = NAME}
  • IF(NAME不存在){使用NAME和SCORE创建新行)

bin*_*yLV 5

我会用insert .. on duplicate key update ...声明.像这样的东西:

insert into highscore set
    name = :name,
    score = :new_score
on duplicate key update
    score = greatest(score, :new_score)
Run Code Online (Sandbox Code Playgroud)

name列应该索引为unique.

测试脚本:

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);
Run Code Online (Sandbox Code Playgroud)

产量select * from player:

+------+-------+
| name | score |
+------+-------+
| bar  |   200 |
| baz  |   100 |
| foo  |   100 |
+------+-------+
Run Code Online (Sandbox Code Playgroud)