MYSQL 逗号分割字段行转列

业务表(A)数据:

id

value

1

01,02

2

03,04

字典表 (B) 数据:

id

value

01

02

03

04

期望得到的结果:

id

value

1

春,夏

2

秋,冬

方法一:

SELECT
    A.id,
    GROUP_CONCAT(B. VALUE)
FROM
    A
LEFT JOIN B ON FIND_IN_SET(B.id, A. VALUE) <> 0
GROUP BY
    A.id

方法二:

SELECT
    a.id,
    GROUP_CONCAT(B. VALUE) value
FROM
    (
        SELECT
            A.id,
            SUBSTRING_INDEX(
                SUBSTRING_INDEX(
                    A.
                    VALUE
                        ,
                        ',',
                        c.help_topic_id + 1
                ),
                ',' ,- 1
            )
        VALUE

        FROM
            A
        LEFT JOIN mysql.help_topic c ON c.help_topic_id < LENGTH(A. VALUE) - LENGTH(REPLACE(A. VALUE, ',', '') + 1)
    ) a
LEFT JOIN B ON a.
VALUE
    = B.id
GROUP BY
    a.id
上一篇:世界卫生组织确认玩电子游戏到这个程度就是“病”了


下一篇:MYSQL存储过程(一)