Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update multiple rows with multiple values and multiple conditions mysql

Tags:

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

I want to update all these in one query.

like image 361
Nadeem Jamali Avatar asked Dec 05 '11 16:12

Nadeem Jamali


2 Answers

Try this:

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 sales
END

Naturally I don't know if date field is really DATE or DATETIME, so I left query showing what you can do, but maybe you have to fix dates comparison according to data type. If date field is DATE (as it should) you can write AND date = '2011-06-22' and so on.
Note ELSE condition: it's necessary to avoid records not falling inside other cases will be set to NULL.

like image 180
Marco Avatar answered Sep 23 '22 13:09

Marco


Rather than write a sql query that is far too complicated and time involved, I believe you would be better off spending your time writing a data access object to handle these rather simple manipulations on a per record basis. This makes later maintenance of the code, along with development of new code using your data access objects far easier than a one time use, intricate sql query.

like image 20
Jason Avatar answered Sep 21 '22 13:09

Jason