Mysql之一行转多行(列转行)--- help_topic

用到的知识点:

substring_index(str,delim,count)

      str:要处理的字符串

      delim:分隔符

      count:计数

例子:str=www.wikibt.com

      substring_index(str,'.',1)

      结果是:www

      substring_index(str,'.',2)

      结果是:www.wikibt

      也就是说,如果count是正数,那么就是从左往右数,第N个分隔符的左边的全部内容

      相反,如果是负数,那么就是从右边开始数,第N个分隔符右边的所有内容,如:

      substring_index(str,'.',-2)

      结果为:wikibt.com

length(str)   获取字符串str的长度

mysql.help_topic

这个表是mysql自带的一个表,具体表的内容可以使用select * from mysql.help_topic;

查看。这里我们只是使用到了他的help_topic_id字段,因为他的help_topic_id字段是从0开始自增的。

原数据如下,将jsondata转成多行,以逗号分割

SELECT
	tp.id,
	substring_index( SUBSTRING_INDEX( tp.jsondata, ',', hp.help_topic_id + 1 ), ',', - 1 ) json 
FROM
	testjson tp
	LEFT JOIN mysql.help_topic hp ON hp.help_topic_id <= length( tp.jsondata ) - length( REPLACE ( tp.jsondata, ',', '' ) );

 结果如下:

Mysql之一行转多行(列转行)--- help_topic_第1张图片

注意:实际使用时,开发环境未必和生产环境的权限一致,此时一定要以生产环境为主,确认生产环境是否有mysql数据库的使用权限,如果没有,创建一个help_topic表,只需要有help_topic_id列,即可满足该功能。

你可能感兴趣的:(mysql,mysql,数据库,database)