MySQL行转列

在MySQL中,有字段存储类型为varchar,值为用某个符号分割的数组,如何进行行转列?

整体思路:利用mysql.help_topic中从0开始自增help_topic_id字段和想要行转列的表进行join产生笛卡尔积,运用MySQL的substring_index(str,delim,count)函数将字段一个一个分割。

substring_index(str,delim,count)
str:要处理的字符串
delim:分隔符
count:计数(如果是正数,从左至右截取count个,负数则从右至左截取count个)

select substring_index('2,3,4,5,6',',',2);
在这里插入图片描述
select substring_index('2,3,4,5,6',',',-2);
在这里插入图片描述

创建测试表

create table test.test_mysql_hangzhuanlie (
  id bigint(20) not null auto_increment comment '主键',
  username varchar(50) default null,
  tags varchar(50) default null,
  primary key (id)
) engine=innodb auto_increment=650 default charset=utf8mb4 comment='测试表'

导入测试数据

insert into test.test_mysql_hangzhuanlie values (1, '李威', '6,9,8'), (2, '李白', '2,6,3');

行转列

select t1.id, t1.username, substring_index(substring_index(t1.tags, ',', t2.help_topic_id + 1), ',',- 1) as tag
  from test.test_mysql_hangzhuanlie as  t1 
  join mysql.help_topic as t2
    on t2.help_topic_id < (length(t1.tags) - length(REPLACE(t1.tags, ',', '')) + 1)
;

在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值