Sql

mysqlは文字列を複数の行に分割しました



Mysql Split String Into Multiple Rows



製品のSKUは、独立していて一意である必要があります。

たとえば、チェーンのSKUはL001、L002、L003であり、ペンダントはD001、D002、D003です。



ただし、歴史的な理由により、一部の製品は組み合わせて販売されており、それらのSKUは他のSKUの組み合わせです。

例:チェーン+ペンダント:L001 + D002、



ただし、カウントする場合は、独立したSKUに従って順序をテーブルに分割する必要があります。

たとえば、注文のSKUはL001 + D002は2行に分割する必要があり、各行のSKUはそれぞれL001とD002です。

まず、mysqlでストアドプロシージャを作成して、結合された製品のレコードを2つに分割し、データベースに挿入しましょう。



DELIMITER $$ USE `aporroreport`$$ DROP PROCEDURE IF EXISTS `sku_split_insert_order`$$ CREATE DEFINER=`root`@`localhost` PROCEDURE `sku_split_insert_order`(sku VARCHAR(255), orderid INT) BEGIN DECLARE sku_num INT #The Sku actually contains multiple skus, separated by +, here only the number of + is calculated DECLARE sku_i INT #temporary variable DECLARE tmp_sku VARCHAR(255) #Sku temporarily split DELETE FROM `sku_orders_products_list` #First empty the table #Originally correct sku_num should be +1, but here because the subscript starts from 1, so +2 SET sku_num = LENGTH(sku) - LENGTH(REPLACE(sku,'+',''))+2 SET sku_i = 1 WHILE sku_i 実行する

CALL sku_split_insert_order( 'L001 + D002'、888)

結果:


最終的なストアドプロシージャ:

DELIMITER $$ USE `aporroreport`$$ DROP PROCEDURE IF EXISTS `test_copy_order`$$ CREATE PROCEDURE `test_copy_order`() BEGIN #Transfer the data of one order table to another table, because the sku in it is actually added by multiple skus, and now it needs to be split #That is: 2 sku combinations are split into 2 lines, and 3 sku combinations are split into 3 lines #--Define the variable that receives the cursor data DECLARE sku VARCHAR(200) #temporary sku DECLARE sku_num INT #The Sku actually contains multiple skus, separated by +, here is the number of independent skus DECLARE sku_i INT #temporary variable DECLARE tmp_sku VARCHAR(255) #Sku temporarily split DECLARE orderid INT #-- Cursor #-- Traverse data end flag DECLARE done INT DEFAULT FALSE #Add alias when querying, otherwise no data can be found DECLARE cur CURSOR FOR SELECT t.sku, t.orderid FROM `aporro_orders_products_list` AS t #-- Bind the end flag to the cursor DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE #-- Open the cursor OPEN cur #-- start loop read_loop:LOOP #-- Extract the data in the cursor FETCH cur INTO sku,orderid #-- At the end of the statement IF done THEN LEAVE read_loop END IF #Count the number of independent skus. The correct sku_num should be +1, but because the subscript of SUBSTRING_INDEX starts from 1, so +2 SET sku_num = LENGTH(sku) - LENGTH(REPLACE(sku,'+',''))+2 SET sku_i = 1 WHILE sku_i