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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With