Generating a range of numbers in MySQL

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

    Very similar to the accepted response, but using the new WITH syntax for mysql >= 8.0 which makes a lot more legible and the intent is also clearer

    WITH DIGITS (N) AS (
      SELECT 0 UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL
      SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL
      SELECT 8 UNION ALL SELECT 9)
    SELECT 
      UNITS.N + TENS.N*10 + HUNDREDS.N*100 + THOUSANDS.N*1000 
    FROM 
      DIGITS AS UNITS, DIGITS AS TENS, DIGITS AS HUNDREDS, DIGITS AS THOUSANDS;
    

提交回复
热议问题