自学内容网 自学内容网

Mysql中如何实现两列的值互换?给你提供些思路。

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

在这里插入图片描述

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

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

UPDATE students
SET name = other_name,
    other_name = name;

结果是这样。。。没搞定
在这里插入图片描述

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

2.1 加第三列?(能解决,但是看起来呆呆)
-- 新增列
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 上临时表(搞点弯路走走)
-- 创建临时表
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

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');

原文地址:https://blog.csdn.net/weixin_45549188/article/details/140716787

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!