Generating a range of numbers in MySQL

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

    The "shortest" way i know (in MySQL) to create a table with a long sequence is to (cross) join an existing table with itself. Since any (common) MySQL server has the information_schema.COLUMNS table i would use it:

    DROP TABLE IF EXISTS seq;
    CREATE TABLE seq (i MEDIUMINT AUTO_INCREMENT PRIMARY KEY)
        SELECT NULL AS i
        FROM information_schema.COLUMNS t1
        JOIN information_schema.COLUMNS t2
        JOIN information_schema.COLUMNS t3
        LIMIT 100000; -- <- set your limit here
    

    Usually one join should be enough to create over 1M rows - But one more join will not hurt :-) - Just don't forget to set a limit.

    If you want to include 0, you should "remove" the AUTO_INCEMENT property.

    ALTER TABLE seq ALTER i DROP DEFAULT;
    ALTER TABLE seq MODIFY i MEDIUMINT;
    

    Now you can insert 0

    INSERT INTO seq (i) VALUES (0);
    

    and negative numbers as well

    INSERT INTO seq (i) SELECT -i FROM seq WHERE i <> 0;
    

    You can validate the numbers with

    SELECT MIN(i), MAX(i), COUNT(*) FROM seq;
    

提交回复
热议问题