问题
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?
回答1:
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));
来源:https://stackoverflow.com/questions/19755906/splitting-mysql-value-into-unknown-number-of-parts