当前位置: 代码网 > it编程>数据库>Mysql > Mysql中如何实现两列的值互换

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

2024年11月12日 Mysql 我要评论
mysql中如何实现两列的值互换如图,因业务要求,需要把某两列的值互换。1、第一感觉此sql应该能处理问题了update studentsset name = other_name, other

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

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com