Generating a range of numbers in MySQL

前端 未结 11 1892
一个人的身影
一个人的身影 2020-11-22 15:07

How do I generate a range of consecutive numbers (one per line) from a MySQL query so that I can insert them into a table?

For example:

nr
1
2
3
4
5
         


        
11条回答
  •  无人共我
    2020-11-22 15:47

    Let's say you want to insert numbers 1 through 100 into your table. As long as you have some other table that has at least that many rows (doesn't matter the content of the table), then this is my preferred method:

    INSERT INTO pivot100 
    SELECT @ROW := @ROW + 1 AS ROW
     FROM someOtherTable t
     join (SELECT @ROW := 0) t2
     LIMIT 100
    ;
    

    Want a range that starts with something other than 1? Just change what @ROW gets set to on the join.

提交回复
热议问题