Generate an integer sequence in MySQL

前端 未结 16 2727
南旧
南旧 2020-11-22 06:47

I need to do a join with a table/result-set/whatever that has the integers n to m inclusive. Is there a trivial way to get that without just buildi

16条回答
  •  灰色年华
    2020-11-22 07:31

    The simplest way to do this is:

    SET @seq := 0;
    SELECT @seq := FLOOR(@seq + 1) AS sequence, yt.*
    FROM your_table yt;
    

    or in one query:

    SELECT @seq := FLOOR(@seq + 1) AS sequence, yt.*
    FROM (SELECT @seq := 0) s, your_table yt;
    

    The FLOOR() function is used here to get an INTEGER in place of a FLOAT. Sometimes it is needed.

    My answer was inspired by David Poor answer. Thanks David!

提交回复
热议问题