MYSQL: sql中某一个字段内容为用逗号分割的字符串转换成多条数据(适用于部分树机构)
短信预约 -IT技能 免费直播动态提醒
创建表的示例
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去重即可获取到需要的相关信息
来源地址:https://blog.csdn.net/qq_29757467/article/details/129693943
免责声明:
① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。
② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341