22

我正在使用以下查询:

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)。
  • 真:更新lastupdate = NOW(),加一programruncount,然后更新ip = :ip
  • False:所有字段都应保持不变。

我不太确定该怎么做,但环顾四周后,我尝试在零件中使用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

4

1 回答 1

57

您错误地使用了 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 的流控制运算符

于 2013-05-16T13:25:13.737 回答