更新DUPLICATE KEY问题

时间:2013-02-21 20:43:34

标签: php mysql query-optimization

我正在努力做到这一点:

$sql = mysql_query("SELECT COUNT(fk_player_id) count FROM wr_year WHERE fk_player_id=$currplayer AND year=2013");
$row = mysql_fetch_assoc($sql);

if($row['count'] == 0){
   mysql_query("INSERT INTO wr_year (fk_player_id, year, points) VALUES ($currplayer, 2013, $points)");
} else {
   mysql_query("UPDATE wr_year SET points=points+$points WHERE fk_player_id=$currplayer AND year=2013");
}

进入这个:

mysql_query("INSERT INTO wr_year (fk_player_id, year, points) VALUES ($currplayer, 2013, $points)
ON DUPLICATE KEY UPDATE points=points+$points");

但是这个工作?如何确保仅在fk_player_id和year上检查ON DUPLICATE,是否可以完成?

提前致谢; - )

2 个答案:

答案 0 :(得分:2)

ON DUPLICATE KEY检查索引违规是否应该插入或更新,因此您需要首先在要检查的两列上创建唯一索引;

CREATE UNIQUE INDEX uix_wr_year ON wr_year (fk_player_id, year);

之后,如果表中已经存在相同的fk_player_id / year组合,它将改为更新。

答案 1 :(得分:0)

使用VALUES功能。

试试这个

     INSERT INTO wr_year (fk_player_id, year, points) VALUES ($currplayer, 2013, $points)
     ON DUPLICATE KEY UPDATE points= VALUES(points+$points)

请参阅http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html