'Split comma separated value from table column into rows using mysql?

I found the post which has the column with 3 values seperated by commas. I will have more than 3 values seperated by commas . For example,

ID    CITY_ID
--------------
1     12,18,16,17,35
2     12,16
....
--------------

Is it possible to split string city_id and make it into rows using mysql query like below

  ID   CITY_ID
  -------------
   1    12
   1    18
   1    16
    ....
   2    16
    ....
  --------------

If yes, Kindly give some advice ....



Solution 1:[1]

Try this

  SELECT ID,SUBSTRING_INDEX(SUBSTRING_INDEX(t.CITY_ID, ',', n.n), ',', -1) value
  FROM Table1 t CROSS JOIN 
  (
   SELECT a.N + b.N * 10 + 1 n
     FROM 
    (SELECT 0 AS N UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9) a
   ,(SELECT 0 AS N UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9) b
    ORDER BY n 
   ) n
 WHERE n.n <= 1 + (LENGTH(t.CITY_ID) - LENGTH(REPLACE(t.CITY_ID, ',', '')))
 ORDER BY ID,value

FIDDLE DEMO

Output:


ID  VALUE
1   12
1   16
1   17
1   18
1   35
2   12
2   16

Solution 2:[2]

Reference: https://gist.github.com/duanehutchins/c6000b367b3032b0b495c46b3bc370c8

Functions:

DROP FUNCTION IF EXISTS `SET_COUNT`;
        
CREATE FUNCTION `SET_COUNT`($strlist MEDIUMBLOB) RETURNS SMALLINT(5) UNSIGNED
NO SQL
DETERMINISTIC
RETURN 1+CHAR_LENGTH($strlist)-CHAR_LENGTH(REPLACE($strlist,',',''));
              
DROP FUNCTION IF EXISTS `SET_EXTRACT`;
             
CREATE FUNCTION `SET_EXTRACT`($i SMALLINT UNSIGNED, $strlist MEDIUMBLOB) RETURNS VARBINARY(255)
NO SQL
DETERMINISTIC
RETURN NULLIF(SUBSTRING_INDEX(SUBSTRING_INDEX(CONCAT(0b0, ',', $strlist, ',', 0b0), ',', $i+1.5*(SIGN($i+0.5)+1)-1), ',', -SIGN($i+0.5)),0b0);

use:

  SELECT SET_EXTRACT(n.digit, 'a,b,c,d,f,g')AS split_value FROM  (SELECT 0 digit 
  UNION ALL SELECT 1 
  UNION ALL SELECT 2 
  UNION ALL SELECT 3  
  UNION ALL SELECT 4 
  UNION ALL SELECT 5 
  UNION ALL SELECT 6
  UNION ALL SELECT 7
  UNION ALL SELECT 8
  UNION ALL SELECT 9
  UNION ALL SELECT 10) AS  n WHERE n.digit < set_count('a,b,c,d,f,g')

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Vignesh Kumar A
Solution 2 Juan Carlos Constantine