Home > Database > Mysql Tutorial > How to Split Comma-Separated Values in a MySQL Column into Separate Rows?

How to Split Comma-Separated Values in a MySQL Column into Separate Rows?

Mary-Kate Olsen
Release: 2024-11-28 07:32:11
Original
725 people have browsed it

How to Split Comma-Separated Values in a MySQL Column into Separate Rows?

Mysql String Split

Problem:

You have a table with a column containing comma-separated values. You want to split these values into separate rows, with each value corresponding to a row.

For example, given the table:

Col1 col2
1 a,b,c
2 d,e

You would like to extract the following rows:

Col1 col2
1 a
1 b
1 c
2 d
2 e

Solution:

This can be achieved using a MySQL stored procedure. The following SQL script includes both the stored procedure and the function it uses:

DELIMITER $$

CREATE FUNCTION strSplit(x VARCHAR(65000), delim VARCHAR(12), pos INTEGER) 
RETURNS VARCHAR(65000)
BEGIN
  DECLARE output VARCHAR(65000);
  SET output = REPLACE(SUBSTRING(SUBSTRING_INDEX(x, delim, pos)
                 , LENGTH(SUBSTRING_INDEX(x, delim, pos - 1)) + 1)
                 , delim
                 , '');
  IF output = '' THEN SET output = null; END IF;
  RETURN output;
END $$


CREATE PROCEDURE BadTableToGoodTable()
BEGIN
  DECLARE i INTEGER;

  SET i = 1;
  REPEAT
    INSERT INTO GoodTable (col1, col2)
      SELECT col1, strSplit(col2, ',', i) FROM BadTable
      WHERE strSplit(col2, ',', i) IS NOT NULL;
    SET i = i + 1;
    UNTIL ROW_COUNT() = 0
  END REPEAT;
END $$

DELIMITER ;
Copy after login

To use this stored procedure, you can run the following query:

CALL BadTableToGoodTable();
Copy after login

This will create a new table called 'GoodTable' with the desired data.

The above is the detailed content of How to Split Comma-Separated Values in a MySQL Column into Separate Rows?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template