Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional UPDATE in MySQL

I am trying to UPDATE values from a table, but I need to add some conditions. I found the function CASE, but I am not if it is the best method.

Here is an example. My table is 'relation':

 userid1 | userid2 | name1 | name2 

I got for example:

SELECT *  FROM relation  WHERE (userid1 = 3 AND userid2 = 4)       OR (userid1 = 4 AND userid2 = 3);   

Output:

 4 | 3 | bill | jack 

and I want to change the name of the user 3 in the relation between 3 and 4, but I don't know if it is the userid1 or the userid2.

I thought of case:

UPDATE relation     CASE WHEN userid1 = 3 THEN SET name1 = 'jack' END          WHEN userid2 = 3 THEN SET name2 = 'jack' END  WHERE (userid1 = 3 AND userid2 = 4)        OR (userid1 = 4 AND userid2 = 3); 

But it doesn't work! Any ideas?

Thanks very much in advance.

like image 583
Pierre Lebon Avatar asked Jun 23 '13 21:06

Pierre Lebon


People also ask

What is conditional update?

Conditional update applies to scenarios where high-concurrency applications are updated. In these scenarios, old_value may be updated by other clients. If you use conditional update, the current value is updated to new_value only when the current value is equal to old_value.

How do you write an update query with if condition?

IF @flag = 1 UPDATE table_name SET column_A = column_A + @new_value WHERE ID = @ID; ELSE UPDATE table_name SET column_B = column_B + @new_value WHERE ID = @ID; This is much easier to read albeit this is a very simple query. Here's a working example courtesy of @snyder: SqlFiddle.

How do I update multiple values in MySQL?

MySQL UPDATE multiple columnsMySQL UPDATE command can be used to update multiple columns by specifying a comma separated list of column_name = new_value. Where column_name is the name of the column to be updated and new_value is the new value with which the column will be updated.


1 Answers

Unfortunately it's not very clear what you want to get in the end, but here is how you could correctly use conditional SET in your UPDATE

UPDATE relation     SET name1 = CASE WHEN userid1 = 3 THEN 'jack' ELSE name1 END,        name2 = CASE WHEN userid2 = 3 THEN 'jack' ELSE name2 END WHERE (userid1 = 3 AND userid2 = 4)     OR (userid1 = 4 AND userid2 = 3); 

Here is SQLFiddle demo.

like image 100
peterm Avatar answered Sep 21 '22 15:09

peterm