Database_SQL Knowledge_Update multiple records at the same time in a statement, using CASE WHEN (each record is updated to a different result)

 

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

Published 519 original articles · praised 1146 · 2.83 million views

Guess you like

Origin blog.csdn.net/u010003835/article/details/103926628