Generating a range of numbers in MySQL

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

    If you need the records in a table and you want to avoid concurrency issues, here's how to do it.

    First you create a table in which to store your records

    CREATE TABLE `incr` (
      `Id` int(11) NOT NULL auto_increment,
      PRIMARY KEY  (`Id`)
    ) ENGINE=MyISAM  DEFAULT CHARSET=utf8;
    

    Secondly create a stored procedure like this:

    DELIMITER ;;
    CREATE PROCEDURE dowhile()
    BEGIN
      DECLARE v1 INT DEFAULT 5;
      WHILE v1 > 0 DO
        INSERT incr VALUES (NULL);
        SET v1 = v1 - 1;
      END WHILE;
    END;;
    DELIMITER ;
    

    Lastly call the SP:

    CALL dowhile();
    SELECT * FROM incr;
    

    Result

    Id
    1
    2
    3
    4
    5
    

提交回复
热议问题