MySql 一行变多行(根据特定符号分割)

您所在的位置:网站首页 一列数据拆分成多列数据 MySql 一行变多行(根据特定符号分割)

MySql 一行变多行(根据特定符号分割)

2024-06-29 08:25| 来源: 网络整理| 查看: 265

一、测试数据 DROP TABLE IF EXISTS `test`; CREATE TABLE IF NOT EXISTS `test` ( `id` bigint(20) NOT NULL AUTO_INCREMENT , `name` varchar(255) DEFAULT NULL, `num` int(8), PRIMARY KEY (`id`) ); INSERT INTO `test`(`name`, `num`) VALUES ('a1,b258,c', 11); INSERT INTO `test`(`name`, `num`) VALUES ('f,g123456,h,i85,j', 33); INSERT INTO `test`(`name`, `num`) VALUES ('d,e1234', 22);

那么: SELECT * FROM test; :

在这里插入图片描述

那么,把数据转换成为下面这样,需要怎么样实现呢:

在这里插入图片描述

二、普通 sql 实现(需要依赖 mysql.help_topic 表) SELECT a.id,a.num,SUBSTRING_INDEX( SUBSTRING_INDEX( a.`name`, ',', b.help_topic_id + 1 ), ',',-1 ) name FROM test a JOIN mysql.help_topic b ON b.help_topic_id < ( LENGTH( a.`name`) - LENGTH( REPLACE ( a.`name`, ',', '' ) ) + 1 ); 三、mysql.help_topic 无权限处理办法

mysql.help_topic 的作用是对 SUBSTRING_INDEX 函数出来的数据(也就是按照分割符分割出来的)数据连接起来做笛卡尔积。

如果 mysql.help_topic 没有权限,可以自己创建一张临时表,用来与要查询的表连接查询。

获取该字段最多可以分割成为几个字符串:

SELECT MAX(LENGTH(a.`name`) - LENGTH(REPLACE(a.`name`, ',', '' )) + 1) FROM `test` a;

创建临时表,并给临时表添加数据:

注意:

临时表必须有一列从 0 或者 1 开始的自增数据临时表表名随意,字段可以只有一个临时表示的数据量必须比 MAX(LENGTH(a.name) - LENGTH(REPLACE(a.name, ',', '' )) + 1) 的值大 DROP TABLE IF EXISTS `tmp_help_topic`; CREATE TABLE IF NOT EXISTS `tmp_help_topic` ( `help_topic_id` bigint(20) NOT NULL AUTO_INCREMENT , PRIMARY KEY (`help_topic_id`) ); INSERT INTO `tmp_help_topic`() VALUES (); INSERT INTO `tmp_help_topic`() VALUES (); INSERT INTO `tmp_help_topic`() VALUES (); INSERT INTO `tmp_help_topic`() VALUES (); INSERT INTO `tmp_help_topic`() VALUES (); INSERT INTO `tmp_help_topic`() VALUES (); INSERT INTO `tmp_help_topic`() VALUES (); INSERT INTO `tmp_help_topic`() VALUES (); INSERT INTO `tmp_help_topic`() VALUES (); INSERT INTO `tmp_help_topic`() VALUES ();

查询:

SELECT a.id,a.num,SUBSTRING_INDEX(SUBSTRING_INDEX(a.`name`, ',', b.help_topic_id), ',',-1 ) name FROM test a JOIN tmp_help_topic b ON b.help_topic_id


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3