条件ON DUPLICATE KEY UPDATE(仅在特定条件为真时更新)

时间:2013-05-16 13:10:59

标签: mysql sql pdo

我使用了以下查询:

INSERT INTO userlist (username, lastupdate, programruncount, ip)
VALUES (:username, NOW(), 1, :ip)
ON DUPLICATE KEY UPDATE
lastupdate = NOW(), programruncount = programruncount + 1, ip = :ip;

但是,我也希望ON DUPLICATE KEY UPDATE有条件,所以它将执行以下操作:

  • IF lastupdate不到20分钟前(lastupdate > NOW() - INTERVAL 20 MINUTE)。
  • True:更新lastupdate = NOW(),向programruncount添加一个,然后更新ip = :ip
  • 错误:所有字段都应保持不变。

我不确定如何做到这一点,但在环顾四周之后,我尝试在IF部分使用ON DUPLICATE KEY UPDATE声明。

INSERT INTO userlist (username, lastupdate, programruncount, ip)
VALUES ("testuser", NOW(), "1", "127.0.0.1")
ON DUPLICATE KEY UPDATE
IF(lastupdate > NOW() - INTERVAL 20 MINUTE, VALUES(lastupdate, programruncount + 1),
lastupdate, programruncount);

但是我收到以下错误:#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'IF(lastupdate > NOW() - INTERVAL 20 MINUTE, VALUES(lastupdate, programruncount +' at line 6

1 个答案:

答案 0 :(得分:31)

你错误地使用了IF语句

INSERT INTO userlist (username, lastupdate, programruncount, ip)
VALUES (:username, NOW(), 1, :ip)
ON DUPLICATE KEY UPDATE
lastupdate = IF(lastupdate > NOW() - INTERVAL 20 MINUTE, NOW(), lastupdate),
programruncount = IF(lastupdate > NOW() - INTERVAL 20 MINUTE, programruncount + 1,   programruncount),
ip = IF(lastupdate > NOW() - INTERVAL 20 MINUTE, :ip, ip);

所以IF检查条件并返回作为参数提供的两个值之一。见MySQL's Flow Control Operators