I encountered a problem today. We have to update multiple records based on different information passed in a List, but the updated value of each record is different.
How should this be achieved?
The main purpose is to update multiple entries at a time to reduce the number of accesses to the database
To simulate the real situation, we created a table
CREATE TABLE `multi_update` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) DEFAULT NULL,
`sex` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4
And insert multiple records
INSERT INTO `multi_update` VALUES (1, 'sx', 'male');
INSERT INTO `multi_update` VALUES (2, 'zx', 'female');
Let's open the table below and check:
We use CASE WHEN to update
UPDATE multi_update
SET
name = (
CASE id
WHEN 1 THEN 'szh'
WHEN 2 THEN 'zyq'
END
)
WHERE id IN (1, 2)
;
Record after update