Reputation: 39
I made a script that auto creates Update statement using For loops and all and the final result executes this:
mysql_query("UPDATE table2
SET(code2='sfvv' WHERE number='1'),
(code2='sdvsdv' WHERE number='2')
WHERE id='32'") or die ( mysql_error() );
The error said: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '(code2='sfvv' WHERE number='1'),(code2='sdvsdv' WHERE number='2') WHERE i' at line 1
Upvotes: 0
Views: 62
Reputation: 43
Update table2
SET code2= CASE
WHEN number=1 THEN 'sfvv'
WHEN number=2 THEN 'sdvsdv'
ELSE code2
END
WHERE id = 32
Hope it helps
Upvotes: 1
Reputation: 12090
You use AND
and OR
statements to combine conditions:
UPDATE table2
SET code2 = 'sfvv'
WHERE
(number = '1'AND code2 = 'sdvsdv')
OR
(number = '2' AND id = '32')
You can update multiple values in the same row by using commas to separate the statements:
UPDATE table2
SET code2 = 'sfvv', code3 = 'abc'
If you need to update different rows based on different conditions, you need to execute multiple queries:
UPDATE table2 SET code2 = 'sfvv' WHERE id = 1;
UPDATE table2 SET code3 = 'abc' WHERE id = 2;
As the other answer mentioned, you can also use case statements in your SET
clause:
UPDATE table2
SET code2 = CASE WHEN number = 1 THEN 'foo' ELSE 'bar' END
But this is not 100% flexible. Use it when it makes sense.
Upvotes: 2
Reputation: 93724
I guess you need case statement
UPDATE table2
SET code2= case number when 1 then 'sfvv' when 2 then 'sdvsdv' END
where id = 32
Upvotes: 2