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两列值互换内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论