Malibur
Malibur

Reputation: 1783

How to update multiple columns with different where clauses in mySQL

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?

Upvotes: 0

Views: 5848

Answers (2)

xQbert
xQbert

Reputation: 35333

Update $table
set meta_value = CASE WHEN meta_key = 'name' then 'john'
                      WHEN meta_key = 'trak' then 'v1234' end
where post_Id = $post_ID 

Upvotes: 4

symcbean
symcbean

Reputation: 48387

UPDATE $table 
SET meta_value = IF(meta_key='name','john','v1234')
WHERE   post_id=$post_id AND
    meta_key IN ('trak','name')

Upvotes: 1

Related Questions