使用'on duplicate key update'子句时,case表达式无法正常工作

时间:2016-12-09 08:27:07

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

通过以下查询,我希望仅当ConcurrentJobs列中的值MaxConcurrentJobs更新greater than or equal to的值时才更新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列中的值concurrent jobs。这可能是什么原因?查询在哪里失败?

2 个答案:

答案 0 :(得分:0)

  

.. ON DUPLICATE KEY UPDATE子句中的VALUES(col_name)引用   要插入的col_name的值,没有重复键   冲突发生了。 VALUES()函数仅在INSERT中有意义   ... UPDATE语句,否则返回NULL   http://dev.mysql.com/doc/refman/5.7/en/insert-on-duplicate.html

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

答案 1 :(得分:0)

您不需要使用VALUES()引用行中已有的列;这是INSERT提供的 new 值。我认为以下内容应该有效:

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