Monday, 10 December 2012

Update multiple rows with multiple values and multiple conditions mysql



Update multiple rows with multiple values and multiple conditions mysql



I am facing a complex situation of SQL queries. The task is to update multiple rows, with multiple values and multiple conditions. Following is the data which I want to update; Field to update: 'sales', condition fields: 'campid' and 'date':
if campid = 259 and date = 22/6/2011 then set sales = $200
else if campid = 259 and date = 21/6/2011 then set sales = $210
else if campid = 260 and date = 22/6/2011 then set sales = $140
else if campid = 260 and date = 21/6/2011 then set sales = $150

Solution:
UPDATE your_table SET sales = CASE 
    WHEN campid = 259 AND date = 22/6/2011 THEN 200
    WHEN campid = 259 AND date = 21/6/2011 THEN 210
    WHEN campid = 259 AND date = 22/6/2011 THEN 140
    WHEN campid = 259 AND date = 21/6/2011 THEN 150
    ELSE salesEND

No comments:

Post a Comment