有条件的重复密钥更新?

编程入门 行业动态 更新时间:2024-10-23 19:21:02
本文介绍了有条件的重复密钥更新?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有类似的东西:

INSERT INTO tbl (count,otherID) VALUES (2,'a') ON DUPLICATE KEY UPDATE count = 2

仅当新值大于当前值时,我才想更新计数.因此,假设已经有一个记录,其计数为:4,otherID为:"a",表示不应触发ON DUPLICATE KEY UPDATE count = 3

I would like to update count only if the new value is greater than the current value. So let's say there is already a record with count: 4 and otherID: 'a' that ON DUPLICATE KEY UPDATE count = 3 should not be triggered

我该如何实现?

我可以使用吗? ... UPDATE count = IF (NEWVALUE > count) NEWVALUE else count

推荐答案

另一个选项:

INSERT INTO tbl (count, otherID) VALUES (2, 'a') ON DUPLICATE KEY UPDATE count = GREATEST(VALUES(count), count) ;

警告::如果count的传递值是NULL(而不是2),则此操作将失败.它将使用NULL更新该列.因此,最好使用IF()或CASE子句.

Warning: This will fail if the passed value for count is NULL (instead of 2). It will update the column with NULL. So, it's better to use the IF() or a CASE clause.

除非您更喜欢(优雅……):

Unless you prefer the (there goes the elegance ...):

ON DUPLICATE KEY UPDATE count = GREATEST(COALESCE(VALUES(count), count), count) ;

更多推荐

有条件的重复密钥更新?

本文发布于:2023-10-23 06:00:19,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1520001.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:密钥   有条件

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!