mysql concat列作为字符串传递

时间:2017-03-06 19:59:21

标签: mysql sql dynamic concat

我需要连接列名称作为字符串传递的列值。我有一个设计糟糕的MySql表的客户端,如下所示:

-------------------------------------------
| id | column_index | c1 | c2 | c3 | .... |c50|

column_index字段是逗号分隔的列名字符串,如c1,c5,c11,我想做的是编写单个选择查询(没有存储过程),只返回连接列根据哪些列被定义为索引的值。

这样的事情:

SELECT id, column_index, CONCAT_WS(',' FOR col_name IN column_index)

是否有任何方法可以为MySql创建类似于它的查询?

1 个答案:

答案 0 :(得分:0)

您的数据结构严重错误。也许你应该努力修复它而不是创建过于复杂的查询。

那说,以下不是很好,但应该有效:

select id, column_index,
       concat_ws(',',
                 (case when find_in_set('c1', column_index) > 0 then c1 end),
                 (case when find_in_set('c2', column_index) > 0 then c2 end),
                 (case when find_in_set('c3', column_index) > 0 then c3 end),
                 . . .
                ) as vals
. . .