mysql 中 有些字段我们用字符串存储,并以指定字符分隔,再使用的时候有时需要拆分字符串,并转成行
问题
https://bbs.csdn.net/topics/398911039
放心没有抄袭,在CSDN上的回答也是我回答的
表数据如下
ID TYPE T1 T2 T3 T4
1 上海,北京 S B S B
想查询成下面这样的
ID TYPE T1 T2 T3 T4
1 上海 S NULL S NULL
1 北京 NULL B NULL B
解决方案
create table test(id int,ttype varchar(50),t1 varchar(10),t2 varchar(10),t3 varchar(10),t4 varchar(10))
insert into test
values(1,‘上海,北京’,‘S’,‘B’,‘S’,‘B’)
SELECT id,
SUBSTRING_INDEX(SUBSTRING_INDEX(ttype,’,’,help_topic_id+1),’,’,-1) AS num
,case when help_topic_id+1 = 1 then t1 else null end as t1
,case when help_topic_id+1 = 2 then t2 else null end as t2
,case when help_topic_id+1 = 1 then t3 else null end as t3
,case when help_topic_id+1 = 2 then t4 else null end as t4
FROM
mysql.help_topic ,test
WHERE
help_topic_id < LENGTH(ttype)-LENGTH(REPLACE(ttype,’,’,’’))+1
思路参照 https://www.cnblogs.com/gered/p/10797012.html 实现
sql server 字符串分割,行转列 传送门 https://www.jianshu.com/p/365496ce93d5