简体   繁体   English

MYSQL根据CASE语句选择列

[英]MYSQL Select columns based on CASE statement

I have a MYSQL query that selects data from my database and repeats one column upto 5 times based on a comma separated value in the table, sometimes there is only one or 2 sometimes all five.我有一个 MYSQL 查询,它从我的数据库中选择数据,并根据表中的逗号分隔值重复一列最多 5 次,有时只有一两个,有时所有五个。

If there is only 2 I end up with the 2nd set of results repeated another 3 times.如果只有 2,我最终将第二组结果再重复 3 次。 I am wanting to amend the query to count the number of substrings in the string and only repeat the code that number of times.我想修改查询以计算字符串中子字符串的数量,并且只重复代码该次数。

The code would be something similar to this -代码将类似于此 -

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

If you are trying to pull options into a column using substring_index() , then:如果您尝试使用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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM