在MySQL中创建“数字表”

时间:2012-03-17 15:43:07

标签: mysql sql

我正在尝试在MySQL中生成一个连续数字的大表。

我只想要2列;主键和数字列,范围为0-X,其中X非常大。约。 64,000行应该这样做。我试过这段代码没有成功:

CREATE TABLE numbers (
   number           INT         NOT NULL
   CONSTRAINT XPKnumbers
      PRIMARY KEY CLUSTERED (number)
    )

INSERT INTO numbers (number) VALUES (0)

DECLARE @i          INT
SET @i = 20

WHILE 0 < @i
   BEGIN
      INSERT INTO numbers (number)
         SELECT number + (SELECT 1 + Max(number) FROM numbers)
            FROM numbers

      SET @i = @i - 1
   END

SELECT * FROM numbers

我收到此错误:

  

#1064 - 您的SQL语法出错;检查与MySQL服务器版本对应的手册,以便在'CONSTRAINT XPKnumbers PRIMARY KEY CLUSTERED(数字)附近使用正确的语法)在第3行插入n'

有人建议让这项工作吗?

4 个答案:

答案 0 :(得分:20)

你缺少分号,逗号,甚至在纠正语法后,每次只是在循环中再插入一行时,从表中选择max仍然不是一个好主意。

删除它并使用http://use-the-index-luke.com/blog/2011-07-30/mysql-row-generator中的生成器:

CREATE OR REPLACE VIEW generator_16
AS SELECT 0 n 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   UNION ALL SELECT 10 UNION ALL SELECT 11 UNION ALL
   SELECT 12  UNION ALL SELECT 13 UNION ALL SELECT 14 UNION ALL 
   SELECT 15;

CREATE OR REPLACE VIEW generator_256
AS SELECT ( ( hi.n << 4 ) | lo.n ) AS n
     FROM generator_16 lo, generator_16 hi;

CREATE OR REPLACE VIEW generator_4k
AS SELECT ( ( hi.n << 8 ) | lo.n ) AS n
     FROM generator_256 lo, generator_16 hi;

CREATE OR REPLACE VIEW generator_64k
AS SELECT ( ( hi.n << 8 ) | lo.n ) AS n
     FROM generator_256 lo, generator_256 hi;

CREATE OR REPLACE VIEW generator_1m
AS SELECT ( ( hi.n << 16 ) | lo.n ) AS n
     FROM generator_64k lo, generator_16 hi;

如果出于某种原因,你真的需要一个数字表来做:

INSERT INTO numbers(number)
SELECT n FROM generator_64k WHERE n < 64000

答案 1 :(得分:0)

您在列和约束声明之间缺少逗号:

CREATE TABLE numbers (
   number           INT         NOT NULL,
   CONSTRAINT XPKnumbers
      PRIMARY KEY CLUSTERED (number)
    )

答案 2 :(得分:0)

从MySQL 8.0开始,您可以使用RECURSIVE CTE生成计数表:

SET @@cte_max_recursion_depth  = 5000;
WITH RECURSIVE cte AS
(
   SELECT 1 AS i
   UNION ALL
   SELECT i+1
   FROM cte
   WHERE i < 3000
)
SELECT *
FROM cte;

<强> DBFiddle Demo

答案 3 :(得分:0)

这是一种生成数字列表的快速简单的方法。使用MySQL运行此查询会在0.561秒内依次产生64,000个数字列表。

set @i = 0;

SELECT * FROM (
SELECT @i:=@i+1 AS IndexNo FROM my_table -- any real table can be used here
HAVING 
@i < 64000
)x