I am trying to run this:
UPDATE test
SET col2=1 WHERE col1='test1',
SET col2=3 WHERE col1='test2';
The error I am getting:
[Err] 1064 - 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 '
My table:
CREATE TABLE `test` (
`col1` varchar(30) NOT NULL,
`col2` int(5) DEFAULT NULL,
PRIMARY KEY (`col1`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
It’s something about ,
at the end of the first row. When I changed it to ;
, it didn’t recognize col2. How can I do this in one query?
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.
First, specify the table name that you want to change data in the UPDATE clause. Second, assign a new value for the column that you want to update. In case you want to update data in multiple columns, each column = value pair is separated by a comma (,). Third, specify which rows you want to update in the WHERE clause.
This is most clear way
UPDATE test
SET col2 = CASE col1
WHEN 'test1' THEN 1
WHEN 'test2' THEN 3
WHEN 'test3' THEN 5
END,
colx = CASE col1
WHEN 'test1' THEN 'xx'
WHEN 'test2' THEN 'yy'
WHEN 'test3' THEN 'zz'
END
WHERE col1 IN ('test1','test2','test3')
Consider using INSERT-ODKU (ON DUPLICATE KEY UPDATE), because that supports to update multiple rows.
Make sure that the values of all PK columns are in the VALUES().
Where feasible, generate the SQL with data from a slave.
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