Search code examples
mysqloptimizationcase

Update multiple rows with multiple 'where' clauses using CASE


I have the following query and want to optimize it. This could be up to 300 or more trips to the database.

update evtentries
  set ro = '1',
  ediv = 'A'
  where 
  entid = '1234' and ID = '10024'

update evtentries
  set ro = '2',
  ediv = 'B'
  where 
  entid = '5678' and ID = '10024'

I have found some information with using case, but not sure how to incorporate it with 2 field on each.

update evtentries
  set ro = CASE WHEN entid = '1234' THEN '1'
                WHEN entid = '5678' THEN '2'
                ELSE ro
                END
     , ediv = 'A'  <---- need to update with the case
WHERE entid IN ('1234', '5678') and ID = '10024'

 

How do I use case or add the ediv field part of this case query?


Solution

  • You do the second column exactly like the first one.

    update evtentries
    set ro = CASE entid
            WHEN '1234' THEN '1'
            WHEN '5678' THEN '2'
            ELSE ro
        END,
        ediv = CASE entid
            WHEN '1234' THEN 'A'
            WHEN '5678' THEN 'B'
            ELSE ediv
        END
    WHERE entid IN ('1234', '5678') and ID = '10024'
    

    You don't really need the ELSE cases since the WHERE clause ensures that only the WHEN clauses will be matched, but there's no harm in keeping it for safety.