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

时间:2011-06-06 14:16:56

标签: php mysql flash

我的表名为“highscore”,如下所示:
nameQL scoreQL
piotr 50

使用NAME和SCORE的Flash游戏以这个名字导出到PHP。

如何在PHP文件中创建:

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

1 个答案:

答案 0 :(得分:5)

我会使用insert .. on duplicate key update ...语句。像这样:

insert into highscore set
    name = :name,
    score = :new_score
on duplicate key update
    score = greatest(score, :new_score)

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

select * from player的输出:

+------+-------+
| name | score |
+------+-------+
| bar  |   200 |
| baz  |   100 |
| foo  |   100 |
+------+-------+