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