Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
243 views
in Technique[技术] by (71.8m points)

opencart - Splitting mysql value into unknown number of parts

I have been given a mySQL database to restructure into an OpenCart installation.

I've pulled most of the data across but in the old site "product categories" have been all put in a single column

|228|243|228|239|228| or |88| or |88|243|

So I have no idea how many would be in any particular record.

I don't want to use a php function to extract this, as I am manually extracting the data with SQL queries into the new database.

An added complication is I have to create a new line in the products_to_categories for each value in the column - I don't mind a multiple step process, I'm not expecting to do this with a single query - I am looking to avoid re-entering all the data.

I know this is similar to MySQL Split String but I don't feel it's a duplicate as that does not answer my question fully as there may be any number of values in the column - not just 2.

[EDIT] I tried common_schema, but at my current level of skill I found it difficult to get the result I was seeking, but I will certainly use it in future. For the record this is closest to my my solution - Can you split/explode a field in a MySQL query?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

One option that I recommend is to use common_schema and specifically functions get_num_tokens() and split_token(), this will help.

Here a simple example of the use that you can adapt for your solution:

/* CODE FOR DEMONSTRATION PURPOSES */

/* Need to install common_schema - code.google.com/p/common-schema/ */ 

/* Procedure structure for procedure `explode1` */     

/*!50003 DROP PROCEDURE IF EXISTS  `explode1` */;

DELIMITER $$

CREATE PROCEDURE `explode1`(str varchar(65500), delim VARCHAR(255))
BEGIN
    DECLARE _iteration, _num_tokens INT UNSIGNED DEFAULT 0;
    DROP TEMPORARY TABLE IF EXISTS `temp_explode`;
    CREATE TEMPORARY TABLE `temp_explode` (`id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT, `word` VARCHAR(200), PRIMARY KEY (`id`));
    SET _num_tokens := (SELECT `common_schema`.`get_num_tokens`(str, delim));
    WHILE _iteration < _num_tokens DO
        SET _iteration := _iteration + 1;
        INSERT INTO `temp_explode` (`word`) SELECT `common_schema`.`split_token`(str, delim, _iteration);
    END WHILE;
    SELECT `id`, `word` FROM `temp_explode`;
    DROP TEMPORARY TABLE IF EXISTS `temp_explode`;
END $$

DELIMITER ;

/* TEST */
CALL `explode1`('Lorem Ipsum is simply dummy text of the printing and typesetting', CHAR(32));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...