MYSQL: sql中某一个字段内容为用逗号分割的字符串转换成多条数据(适用于部分树机构)

1.创建表的示例

 CREATE TABLE tbl_name(
     id       int(11)    not null auto_increment,
     userName varchar(100)    not null,
 PRIMARY KEY(id)
 )
 ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
 
 insert into tbl_name values (1,'a,aa,aaa');
 insert into tbl_name values (2,'b,bb');
 insert into tbl_name values (3,'c,cc')

数据如下图:
在这里插入图片描述
SELECT a.id,SUBSTRING_INDEX(SUBSTRING_INDEX(a.userName,‘,’,b.help_topic_id+1),‘,’,-1) as name
from tbl_name a left join mysql.help_topic b
on b.help_topic_id < (LENGTH(a.userName)-LENGTH(REPLACE(a.userName,‘,’,‘’))+1)
ORDER BY a.id;
在这里插入图片描述

本人需求为 图层树的父级节点都在 ancestors 字段中,需要获取多个图层中信息的不重复的父级节点即可使用

DROP TABLE IF EXISTS `map_two_layer`;
CREATE TABLE `map_two_layer`  (
  `layer_id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '图层ID',
  `node_types` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '节点类型(0目录1服务)',
  `parent_id` bigint(20) NULL DEFAULT NULL COMMENT '父级ID',
  `ancestors` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT '' COMMENT '祖级列表'
  PRIMARY KEY (`layer_id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 1732 CHARACTER SET = utf8 COLLATE = utf8_general_ci COMMENT = '图层注册' ROW_FORMAT = DYNAMIC;

SET FOREIGN_KEY_CHECKS = 1;

主要表结构如下:

在这里插入图片描述

	SELECT DISTINCT (SUBSTRING_INDEX(SUBSTRING_INDEX(a.ancestors,',',b.help_topic_id+1),',',-1) ) as name
 from map_two_layer a left join mysql.help_topic b
 on b.help_topic_id < (LENGTH(a.ancestors)-LENGTH(REPLACE(a.ancestors,',',''))+1)  ORDER BY a.layer_id ;

查询后对主键ID去重即可获取到需要的相关信息
在这里插入图片描述