【问题标题】:mysql concat columns passed as stringsmysql concat 列作为字符串传递
【发布时间】:2017-07-26 20:17:56
【问题描述】:

我需要连接列名作为字符串传递的列值。我有一个客户,他的 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 创建一个类似的查询?

【问题讨论】:

    标签: mysql sql dynamic concat


    【解决方案1】:

    您的数据结构出现严重问题。也许您应该努力解决这个问题,而不是创建过于复杂的查询。

    也就是说,以下内容并不漂亮,但应该可以:

    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
    . . .
    

    【讨论】:

    • 你在id,之后是否缺少@colnames = column_index,
    • @Uueerdo 。 . .我只是没有将column_index 解释为列名。奇怪的数据结构。
    • 我同意这种结构是严重错误的。然而,这是我客户的生产数据库,我在那里只有读取权限,所以我不能修改它。这就是为什么我需要使用复杂的 sql。
    猜你喜欢
    • 1970-01-01
    • 2019-01-20
    • 1970-01-01
    • 1970-01-01
    • 2022-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多