Generating a range of numbers in MySQL

前端 未结 11 1847
一个人的身影
一个人的身影 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:52

    All other answers are good, however they all have speed issues for larger ranges because they force MySQL to generate every number then filter them.

    The following only makes MySQL generate the numbers that are needed, and therefore is faster:

    set @amount = 55; # How many numbers from zero you want to generate
    
    select `t0`.`i`+`t1`.`i`+`t2`.`i`+`t3`.`i` as `offset`
    from
    (select 0 `i` union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) `t0`,
    (select 0 `i` union select 10 union select 20 union select 30 union select 40 union select 50 union select 60 union select 70 union select 80 union select 90) `t1`,
    (select 0 `i` union select 100 union select 200 union select 300 union select 400 union select 500 union select 600 union select 700 union select 800 union select 900) `t2`,
    (select 0 `i` union select 1000 union select 2000 union select 3000 union select 4000 union select 5000 union select 6000 union select 7000 union select 8000 union select 9000) `t3`
    where `t3`.`i`<@amount
    and `t2`.`i`<@amount
    and `t1`.`i`<@amount
    and `t0`.`i`+`t1`.`i`+`t2`.`i`+`t3`.`i`<@amount;
    

    With the above you can generate upto 10,000 numbers (0 to 9,999) with no slower speed overhead for lower numbers, regardless how low they are.

提交回复
热议问题