在Mysql中生成Series,如何在查询时添加自动增量?

时间:2015-11-19 20:59:46

标签: mysql series

我有一个包含数字x的列(c5)的表,我需要一个重复相同行x次的SQL表达式:

我的表A包含:

c1  c2  c3  c4  c5
16  1   2   16  3
16  1   2   17  2 
16  1   2   18  1

我需要:

c1  c2  c3  c4  c5  n
16  1   2   16  3   1
16  1   2   16  3   2
16  1   2   16  3   3
16  1   2   17  2   1
16  1   2   17  2   2
16  1   2   18  1   1

1 个答案:

答案 0 :(得分:0)

我用SQL表达式解决了这个问题:

SELECT
    c1, c2, c3, c4, c5, row_number AS n
FROM
    (
        SELECT
            @curRow := @curRow + 1 AS row_number
        FROM
            tablea
        JOIN (SELECT @curRow := 0) r
        WHERE
            @curRow < (
                SELECT
                    max(c5)
                FROM
                    tablea
            )
    ) AS vwtable2
LEFT JOIN tablea d ON vwtable2.row_number <= tablea.c5;