当前位置:Gxlcms > 数据库问题 > Mysql group_concat函数列转行,与行转列

Mysql group_concat函数列转行,与行转列

时间:2021-07-01 10:21:17 帮助过:279人阅读

    CREATE TABLE digits (digit INT(1));
    INSERT INTO digits
    VALUES
        (0),
        (1),
        (2),
        (3),
        (4),
        (5),
        (6),
        (7),
        (8),
        (9);
    CREATE TABLE sequence (seq INT(3));
    INSERT INTO sequence (
        SELECT
            D1.digit + D2.digit * 10
        FROM
            digits D1
        CROSS JOIN digits D2
    );
技术分享

配置表sequence的结果为0-99的一列数字:

技术分享

SQL:

技术分享
SELECT
    SUBSTRING_INDEX(
        SUBSTRING_INDEX(JoinEventIds, ‘,‘, seq),
        ‘,‘ ,- 1
    ) JoinEventIds
FROM
    sequence
CROSS JOIN user
WHERE
    seq BETWEEN 1
AND (
    SELECT
        1 + LENGTH(JoinEventIds) - LENGTH(
            REPLACE (JoinEventIds, ‘,‘, ‘‘)
        )
)
技术分享

方法二(自己不想建表,图省事):将sequence替换为SELECT @rownum:=@rownum+1 AS seq FROM (SELECT @rownum:=0) r, user  LIMIT 0,100) ,user为表名,这张表需要大于100条。

技术分享
SELECT  SUBSTRING_INDEX(
            SUBSTRING_INDEX(JoinEventIds, ‘,‘, seq),
            ‘,‘ ,- 1
        ) JoinEventIds
    FROM
        (SELECT @rownum:=@rownum+1 AS seq FROM (SELECT @rownum:=0) r, user  LIMIT 0,100) b
    CROSS JOIN user
    WHERE
        seq BETWEEN 1
    AND (
        SELECT
            1 + LENGTH(JoinEventIds) - LENGTH(REPLACE(JoinEventIds, ‘,‘, ‘‘))) 
技术分享

两种方法结果均为:

技术分享

Mysql group_concat函数列转行,与行转列

标签:数列   替换   values   images   ble   cat   行转列   表名   code   

人气教程排行