mysql把逗號分隔的數據變成獨立數據存入關係表

目前有content表裏存了一個字段category_id,是多個數據按照“,”分隔的,但是業務需求變更,這個字段的類型不在是單一的了。

也就是以前的表結構

以前的表結構(content)

id category_id type
1 129,123,111 0
2 341,890,125 1

現在想要這樣的(預期表)

id category_id type
1 129 0
1 123 0
1 111 0
2 341 1
2 890 1
2 125 1

 

本來以爲會很難,結果我發現了這篇微博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

原理類的東西我還沒搞懂,大家有知道的評論告訴我吧

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章