0

Through the following query, I want to update the ConcurrentJobs column only when the value in MaxConcurrentJobs column is greater than or equal to the value of ConcurrentJobs being updated.

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

But the above query doesn't work as expected. It always updates the value 2300 in the concurrent jobs column even if the condition fails. What could be the reason for this? Where does the query fail?

Suhail Gupta
  • 22,386
  • 64
  • 200
  • 328

2 Answers2

0

..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

Since values(MaxConcurrentJobs) refers to a column you are NOT inserting it is NULL so your condition always defaults to values(ConcurrentJobs).Use a trigger for that logic.

Mihai
  • 26,325
  • 7
  • 66
  • 81
0

You don't need to refer columns already in the row using VALUES(); that is for the new values in supplied by the INSERT. I think the following should work:

insert into userjobinfo (UserId,ConcurrentJobs)
    values (335, 2300)
    on duplicate key update
        ConcurrentJobs = (case when MaxConcurrentJobs >= VALUES(ConcurrentJobs)
                               then VALUES(ConcurrentJobs)
                               else ConcurrentJobs
                          end);
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786