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

Conditional ON DUPLICATE KEY UPDATE (Update only if certain condition is true)(Conditional ON DUPLICATE KEY UPDATE(仅在特定条件为真时更新))
本文介绍了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(),给programrunco​​unt 加一个,然后更新ip = :ip.
  • 错误:所有字段都应保持不变.
  • IF lastupdate was less than 20 minutes ago (lastupdate > NOW() - INTERVAL 20 MINUTE).
  • True: Update lastupdate = NOW(), add one to programruncount and then update ip = :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, programrunco​​unt +' 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(仅在特定条件为真时更新)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Execute complex raw SQL query in EF6(在EF6中执行复杂的原始SQL查询)
Hibernate reactive No Vert.x context active in aws rds(AWS RDS中的休眠反应性非Vert.x上下文处于活动状态)
Bulk insert with mysql2 and NodeJs throws 500(使用mysql2和NodeJS的大容量插入抛出500)
Flask + PyMySQL giving error no attribute #39;settimeout#39;(FlASK+PyMySQL给出错误,没有属性#39;setTimeout#39;)
auto_increment column for a group of rows?(一组行的AUTO_INCREMENT列?)
Sort by ID DESC(按ID代码排序)