11

When I have string list like 1, 2, 3... I'd like to use this as one column

Ids
1
2
3

Is it possible by sql query?

ex) SELECT Ids from (1, 2, 3...) <- I know this is not working.

Mihai
  • 24,788
  • 7
  • 64
  • 78
Bewan
  • 113
  • 1
  • 1
  • 7
  • Possible duplicate of [What is the opposite of GROUP\_CONCAT in MySQL?](https://stackoverflow.com/questions/17308669/what-is-the-opposite-of-group-concat-in-mysql) – philipxy Jul 07 '19 at 20:04

3 Answers3

13

Use a subquery of arbitrary digits to split your string.Instead of vals you can use '1,2,3'.

SELECT
  DISTINCT SUBSTRING_INDEX(SUBSTRING_INDEX(vals, ',', n.digit+1), ',', -1) val
FROM
  tt1
  INNER JOIN
  (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) n
  ON LENGTH(REPLACE(vals, ',' , '')) <= LENGTH(vals)-n.digit;

See it working

Mihai
  • 24,788
  • 7
  • 64
  • 78
6

For MySQL 8.0.4+

SELECT *
FROM
  JSON_TABLE(
          CONCAT('[', '1,2,3,4', ']'),
          "$[*]"
          COLUMNS(
              ids BIGINT(20) PATH "$"
              )
      ) AS tt

Concatenate square brackets ([]) around your string to make it into a JSON array. Then use JSON_TABLE to convert it into a table. See the MySQL JSON Table Functions for more info.

Dmitry
  • 6,196
  • 14
  • 37
  • 37
0

You can use below stored procedure to split string delimted by any character:

CREATE PROCEDURE `split_delimited` (
IN inputstr NVARCHAR(1000),
IN delimiter CHAR(1)
)
BEGIN
DROP TEMPORARY TABLE Items;
CREATE TEMPORARY TABLE Items(item NVARCHAR(50)); 
WHILE LOCATE(delimiter,inputstr) > 1 DO
INSERT INTO Items SELECT SUBSTRING_INDEX(inputstr,delimiter,1);
SET inputstr = REPLACE (inputstr, (SELECT LEFT(inputstr,LOCATE(delimiter,inputstr))),'');
END WHILE;
INSERT INTO Items(item) VALUES(inputstr);
select * from Items;
END

Input: 'a,b,c' Output: a b c

singhk
  • 1
  • 1