当前位置:首页 > 站长知识 > 数据库 > 正文内容

mysql中实现两列的值互换的方法

2024-11-29数据库37

Mysql中如何实现两列的值互换

如图,因业务要求,需要把某两列的值互换。

1、第一感觉此sql应该能处理问题了

1
2
3
UPDATE students
SET name = other_name,
    other_name = name;

结果是这样。。。没搞定

2、需要一个地方存要替换的值,不然两列搞不定

2.1 加第三列?(能解决,但是看起来呆呆)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
-- 新增列
ALTER TABLE students
ADD COLUMN swap_col VARCHAR(255);
 
-- 赋值
UPDATE students
SET swap_col = other_name;
 
UPDATE students
SET other_name = name;
 
UPDATE students
SET name = swap_col;
 
-- 删除列
ALTER TABLE students
DROP COLUMN swap_col;
--

2.2 上临时表(搞点弯路走走)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
-- 创建临时表
CREATE TEMPORARY TABLE `students_temp`
(
    `id`         int,
    `name`       varchar(255),
    `other_name` varchar(255),
    INDEX `idx_id` (`id`),
    INDEX `idx_name` (`name`),
    INDEX `idx_other_name` (`other_name`)
);
 
-- 给临时表赋值
INSERT INTO students_temp
SELECT id, name, other_name
FROM students;
 
-- 联表更新
UPDATE students AS target
    INNER JOIN students_temp AS source
    ON target.id = source.id
SET target.name       = source.other_name,
    target.other_name = source.name;
 
-- 删除临时表
DROP TABLE students_temp;

示例sql

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
DROP table if exists `students`;
 
CREATE TABLE `students` (
  `id` int NOT NULL AUTO_INCREMENT,
  `name` varchar(255) DEFAULT NULL,
  `other_name` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`) USING BTREE
);
 
INSERT INTO `students` VALUES (1, '张三', '张三1');
INSERT INTO `students` VALUES (2, '李四', '李四1');
INSERT INTO `students` VALUES (3, '王五', '王五1');
INSERT INTO `students` VALUES (4, '赵六', '赵六');
INSERT INTO `students` VALUES (5, '孙七', '孙七');
INSERT INTO `students` VALUES (6, '张三', '张三2');
INSERT INTO `students` VALUES (7, '李四', '李四2');
INSERT INTO `students` VALUES (8, '张三', '张三3');