Mysql中如何实现两列的值互换
作者:无敌小肥007
这篇文章主要来和大家探讨一下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');
到此这篇关于Mysql中如何实现两列的值互换的文章就介绍到这了,更多相关Mysql两列值互换内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
