-1

我正在努力做到这一点:

$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,并且可以完成吗?

提前致谢 ;-)

4

2 回答 2

2

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

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

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

于 2013-02-21T20:46:51.100 回答
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

于 2013-02-21T20:56:33.637 回答