mysql把逗号分隔的数据变成独立数据存入关系表

目前有content表里存了一个字段category_id,是多个数据按照“,”分隔的,但是业务需求变更,这个字段的类型不在是单一的了。

也就是以前的表结构

以前的表结构(content)

idcategory_idtype
1129,123,1110
2341,890,1251

现在想要这样的(预期表)

idcategory_idtype
11290
11230
11110
23411
28901
21251

 

本来以为会很难,结果我发现了这篇微博https://www.cnblogs.com/yvanBk/p/8555445.html

真的是直接解决了我的问题,再次感谢此博客博主【手动感谢】

贴一下怎么实现的把,首先要先创建一个新的关系表

CREATE TABLE `n_category_relation` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键id',
  `n_id` varchar(6) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT '' COMMENT 'nid',
 `type` int(3) unsigned DEFAULT NULL COMMENT '类型',
  `category_id` varchar(100) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL DEFAULT '' COMMENT '类目id',
  `create_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  `update_time` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '修改时间',
 
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci COMMENT='关系表';

大概就像上面的ddl语句一样吧

n_category_relation表里

n_id对应content表的id,category_id对应category_id,type对应type

 

下面关键sql来了,这个是先按照预期表需要的查询出数据来

SELECT id as n_id,
    substring_index( substring_index( a.category_id, ',', b.help_topic_id + 1 ), ',',- 1 ) as category_id, type,create_time,update_time
FROM
    content a
     JOIN mysql.help_topic b ON b.help_topic_id < ( length( a.category_id ) - length( REPLACE ( a.category_id , ',', '' ) ) + 1)
		 where a.type is not null

然后插入数据,插入完整sql

insert into n_category_relation (n_id,category_id,type,create_time,update_time) 
SELECT id as n_id,
    substring_index( substring_index( a.category_id, ',', b.help_topic_id + 1 ), ',',- 1 ) as category_id, type,create_time,update_time
FROM
    content a
     JOIN mysql.help_topic b ON b.help_topic_id < ( length( a.category_id ) - length( REPLACE ( a.category_id , ',', '' ) ) + 1)
		 where a.type is not null

原理类的东西我还没搞懂,大家有知道的评论告诉我吧

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值