欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Mysql 列转行

程序员文章站 2024-03-01 16:43:46
...

今天逛OSC的时候看见一个有意思的提问(https://www.oschina.net/question/2312022_2215630),Mysql列转行,提问内容如下:

mysql一条记录拆分成多条

我查出来的结果如下
id   relativeIds
2       10,15,21
能不能改成如下结果
id   relativeIds
2       10
2       15
2       21
直接在sql里面改 行不 ?

 这样的需求比较少见,原因就是这种表结构的设计连第一范式都违反了,但苦逼的程序员遇到问题总要解决不是,下面送上一段SQL

select a.id,substring_index(substring_index(a.relativeIds,',',b.help_topic_id+1),',',-1) 
from 
crm_user a
join
mysql.help_topic b
on b.help_topic_id < (length(a.relativeIds) - length(replace(a.relativeIds,',',''))+1)
order by a.id;

 

转载于:https://my.oschina.net/pengdake/blog/1499665