mysql - Case 表达式无法按预期使用 'on duplicate key update' 子句

标签 mysql sql on-duplicate-key case-expression

通过以下查询,我希望仅当 MaxConcurrentJobs 列中的值大于或等于 时才更新 ConcurrentJobs 列正在更新 ConcurrentJobs 的值。

insert into userjobinfo (UserId,ConcurrentJobs) values (335,2300)
            on duplicate key update ConcurrentJobs = case when values(MaxConcurrentJobs) >= ConcurrentJobs
                                    then ConcurrentJobs else values(ConcurrentJobs) end;

但是上面的查询没有按预期工作。即使条件失败,它也始终会更新并发作业列中的值2300。这可能是什么原因?哪里查询失败了?

最佳答案

..VALUES(col_name) in the ON DUPLICATE KEY UPDATE clause refers to the value of col_name that would be inserted, had no duplicate-key conflict occurred. The VALUES() function is meaningful only in INSERT ... UPDATE statements and returns NULL otherwise http://dev.mysql.com/doc/refman/5.7/en/insert-on-duplicate.html

由于 values(MaxConcurrentJobs) 引用了您未插入的列,因此它为 NULL,因此您的条件始终默认为 values(ConcurrentJobs)。对该逻辑使用触发器.

关于mysql - Case 表达式无法按预期使用 'on duplicate key update' 子句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41056090/

相关文章:

php - ON DUPLICATE KEY UPDATE - 当 if 语句为 true - 更新列,否则触发 1062 错误以捕获重复

MySQL 使用 join 返回不正确的数据

mysql - 如何优化mysql Distinct?

sql - 在 PostgreSQL 中查找最大/最小对

mysql - ON DUPLICATE KEY 无法正常工作

MySQL:INSERT ON DUPLICATE KEY UPDATE 并非所有字段

php - 使用 Where 子句插入

php - 显示来自两个表(菜单和子菜单)的数据

php - 查询 MySQL 表

mysql - 为什么SQL中没有 "first greater/less than [or equal to]"比较运算符?