Question

I have a pretty big query I'm trying to optimize.

It's an INSERT INTO ... ON DUPLICATE KEY UPDATE. However, I need to only update the line on certain condition. Since I know that you can't use WHERE with ON DUPLICATE KEY UPDATE, I am using IF.

But I need to update two columns based on the exactly same condition. The problem is that the condition is veery long. It's column1 IN (massive joined select). And having it twice there doesn't seem right either. I would create a temporary table instead, but since this is only needed in the UPDATE part and not the INSERT one, that would create unnecesary work for some cases.

My question is:

How can I update multiple columns based on single condition in ON DUPLICATE KEY UPDATE.

Was it helpful?

Solution

The update statement can refer to values in the from clause of insert . . . select. The idea is to take your query and make it a subquery. Then add one more column which is your calculated column. You can use this in the set clause:

insert into table(col1, . . .)
    select . . .
    from  (select cols, . . .,
                  col1 in (complicated stuff here) as IsPresent
           from . . .
          ) t
     on duplicate key update colx = if(t.IsPresent, a, b), coly(if.tIsPresent, d, e);

Of course, you may be able to get rid of the subquery (which has its own overhead), but this is the most general approach from your description.

OTHER TIPS

According to this Documentation you can update more columns

INSERT INTO table (a,b,c) VALUES (1,2,3)
ON DUPLICATE KEY UPDATE id=LAST_INSERT_ID(id), c=3
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top