Conditional ON DUPLICATE KEY UPDATE (Update only if certain condition is true)(Conditional ON DUPLICATE KEY UPDATE(仅在特定条件为真时更新))
问题描述
我使用了以下查询:
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 成为条件,所以它会执行以下操作:
However, I also want to make the ON DUPLICATE KEY UPDATE conditional, so it will do the following:
- IF
lastupdate不到 20 分钟前(lastupdate > NOW() - INTERVAL 20 MINUTE). - True: 更新
lastupdate = NOW(),给programruncount加一个,然后更新ip = :ip. - 错误:所有字段都应保持不变.
- IF
lastupdatewas less than 20 minutes ago (lastupdate > NOW() - INTERVAL 20 MINUTE). - True: Update
lastupdate = NOW(), add one toprogramruncountand then updateip = :ip. - False: All fields should be left the same.
我不太确定我会怎么做,但环顾四周后,我尝试在 ON DUPLICATE KEY UPDATE 部分使用 IF 语句.
I am not really sure how I would do this but after looking around, I tried using an IF Statement in the ON DUPLICATE KEY UPDATE part.
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 - 您的 SQL 语法有错误;检查与您的 MySQL 服务器版本相对应的手册,了解在 'IF(lastupdate > NOW() - INTERVAL 20 MINUTE, VALUES(lastupdate, programruncount +' at line 6
推荐答案
你使用的 IF 语句不正确
you're using IF statement incorrectly
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 的流量控制运算符.
so IF checks for a condition and return one of two values provided as it's parameters. See MySQL's Flow Control Operators.
这篇关于Conditional ON DUPLICATE KEY UPDATE(仅在特定条件为真时更新)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Conditional ON DUPLICATE KEY UPDATE(仅在特定条件为真时更新)
基础教程推荐
- CHECKSUM 和 CHECKSUM_AGG:算法是什么? 2021-01-01
- ORA-01830:日期格式图片在转换整个输入字符串之前结束/选择日期查询的总和 2021-01-01
- MySQL 5.7参照时间戳生成日期列 2022-01-01
- 使用 VBS 和注册表来确定安装了哪个版本和 32 位 2021-01-01
- 从字符串 TSQL 中获取数字 2021-01-01
- while 在触发器内循环以遍历 sql 中表的所有列 2022-01-01
- 如何在 CakePHP 3 中实现 INSERT ON DUPLICATE KEY UPDATE aka upsert? 2021-01-01
- MySQL根据从其他列分组的值,对两列之间的值进行求和 2022-01-01
- 带有WHERE子句的LAG()函数 2022-01-01
- 带更新的 sqlite CTE 2022-01-01
