在mysql中,将逗号分隔的字符串分割成行

时间:2023-01-28 00:17:06

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

当我有像1 2 3这样的字符串列表…我想把它作为一列。

Ids
1
2
3

Is it possible by sql query?

是否可以通过sql查询?

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

从(1,2,3…)中选择id <-我知道这行不通。

1 个解决方案

#1


3  

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

使用任意数字的子查询来分割字符串。你可以用“1,2,3”代替“vals”。

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

看到它工作

#1


3  

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

使用任意数字的子查询来分割字符串。你可以用“1,2,3”代替“vals”。

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

看到它工作