0

im trying to update multiple columns in a table that all needs different where clauses in single query. Im not amazing at sql, and struggle to find help on google. im trying to achieve something like this

UPDATE $table 
SET meta_value = 'john',
    meta_value = 'v1234'
WHERE   meta_key = 'name' AND post_id=$post_id,
        meta_key = 'trak' AND post_id=$post_id"

the idea being that the first SET matches the first WHERE, and the 2nd SET matches the 2nd WHERE etc.. ideally id be able to do many of these. any idea how I can achieve this?

Malibur
  • 1,695
  • 5
  • 22
  • 31

2 Answers2

4
Update $table
set meta_value = CASE WHEN meta_key = 'name' then 'john'
                      WHEN meta_key = 'trak' then 'v1234' end
where post_Id = $post_ID 
xQbert
  • 34,733
  • 2
  • 41
  • 62
1
UPDATE $table 
SET meta_value = IF(meta_key='name','john','v1234')
WHERE   post_id=$post_id AND
    meta_key IN ('trak','name')
symcbean
  • 47,736
  • 6
  • 59
  • 94
  • This seems to work, thanks! Would you be able to explain it a little bit. What does the expressions in the IF clause mean exactly? And how is this for performance if Im updating 50 different meta_keys? – Malibur Mar 13 '15 at 19:52
  • ahh. just realised that this would only work if its just 2 columns. But I have 500 columns that I'd like to update in one go – Malibur Mar 13 '15 at 19:59
  • Really? 500 *columns*? Then your schema needs fixed. – symcbean Mar 13 '15 at 20:02
  • ups that was suppose to 50 values not 500 columns, sorry – Malibur Mar 13 '15 at 20:17