我有一个MYSQL查询,该查询从数据库中选择数据并根据表中的逗号分隔值最多重复一列,最多5次,有时只有一两个,有时只有五个。
如果只有2个,我最终将第二组结果再重复3次。我想修改查询以计算字符串中子字符串的数量,只重复该次数的代码。
代码将类似于此-
Select name, age, location, options
CASE WHEN options = 5
THEN option1, option2, option3, option4, option5
ELSE WHEN options = 4
THEN option1, option2, option3, option4
ELSE END FROM test_table
答案 0 :(得分:0)
如果您尝试使用substring_index()
将选项拉入列,则:
select t.*,
substring_index(options, 1, ',') as option_1,
(case when options like '%,%'
then substring_index(substring_index(options, 2, ','), ',', -1)
end) as option_2,
(case when options like '%,%,%'
then substring_index(substring_index(options, 3, ','), ',', -1)
end) as option_3,
. . .
from test_table t;