将逗号分隔的列表分隔为查询列

时间:2014-08-20 18:57:32

标签: mysql sql

我有一个表,其中的列包含逗号分隔列表,如

ID :  List 
1  :  1,2,44,5      --row# 1
2  :  4,3,5,2,56,66 --row# 2

等等。我想写一个select查询,它最多有10列Item1,Item2,Item3 .... Item10,每列都有一个来自相应逗号分隔列表的数字。

例如:for ID = 1

Item1 = 1, Item2 = 2, Item3 = 44, Item4 = 55 and all other columns would be null or empty

如何在SQL中编写?

2 个答案:

答案 0 :(得分:4)

你可以这样做:

select
    substring_index(substring_index(str,',',1),',',-1)AS c1
,   CASE WHEN LENGTH(str)-LENGTH(REPLACE(str,',','')) >= 1 THEN substring_index(substring_index(str,',',2),',',-1) ELSE NULL END AS c2
,   CASE WHEN LENGTH(str)-LENGTH(REPLACE(str,',','')) >= 2 THEN substring_index(substring_index(str,',',3),',',-1) ELSE NULL END AS c3
,   CASE WHEN LENGTH(str)-LENGTH(REPLACE(str,',','')) >= 3 THEN substring_index(substring_index(str,',',4),',',-1) ELSE NULL END AS c4
,   CASE WHEN LENGTH(str)-LENGTH(REPLACE(str,',','')) >= 4 THEN substring_index(substring_index(str,',',5),',',-1) ELSE NULL END AS c5
,   CASE WHEN LENGTH(str)-LENGTH(REPLACE(str,',','')) >= 5 THEN substring_index(substring_index(str,',',6),',',-1) ELSE NULL END AS c6
,   CASE WHEN LENGTH(str)-LENGTH(REPLACE(str,',','')) >= 6 THEN substring_index(substring_index(str,',',7),',',-1) ELSE NULL END AS c7
,   CASE WHEN LENGTH(str)-LENGTH(REPLACE(str,',','')) >= 7 THEN substring_index(substring_index(str,',',8),',',-1) ELSE NULL END AS c8
,   CASE WHEN LENGTH(str)-LENGTH(REPLACE(str,',','')) >= 8 THEN substring_index(substring_index(str,',',9),',',-1) ELSE NULL END AS c9
,   CASE WHEN LENGTH(str)-LENGTH(REPLACE(str,',','')) >= 9 THEN substring_index(substring_index(str,',',10),',',-1) ELSE NULL END AS c10
from test

Demo.

表达式有两个共同部分:

  • LENGTH(str)-LENGTH(REPLACE(str,',','')) >= K - 此子表达式确定字符串是否至少包含K分隔符
  • substring_index(substring_index(str,',',K),',',-1) - 此子表达式会在K - 分隔符
  • 之后删除该元素

答案 1 :(得分:1)

这可以通过从MySQL Split String Function创建用户定义的函数引用来完成,将包含逗号分隔字符串的列作为第一个参数传递给此函数,在第二个参数中传递分隔符,在您的情况下逗号是分隔符并在第三个参数中传递您想要的位置以获得字符串

  

SPLIT_STR(字符串,分隔符,位置)

CREATE FUNCTION SPLIT_STR(
  x VARCHAR(255),
  delim VARCHAR(12),
  pos INT
)
RETURNS VARCHAR(255)
RETURN REPLACE(SUBSTRING(SUBSTRING_INDEX(x, delim, pos),
       LENGTH(SUBSTRING_INDEX(x, delim, pos -1)) + 1),
       delim, '');

然后您可以在下面查询您的数据

SELECT 
SPLIT_STR(List, ',', 1) item1,
SPLIT_STR(List, ',', 2) item2,
SPLIT_STR(List, ',', 3) item3,
SPLIT_STR(List, ',', 4) item4,
SPLIT_STR(List, ',', 5) item5,
SPLIT_STR(List, ',', 6) item6,
SPLIT_STR(List, ',', 7) item7,
SPLIT_STR(List, ',', 8) item8,
SPLIT_STR(List, ',', 9) item9,
SPLIT_STR(List, ',', 10) item10
FROM t

Fiddle Demo