2012-03-17 149 views
9

我試圖在mysql中生成一個連續數字的大表。我只想要2列;一個主鍵和一個範圍爲0-X的數字列,其中X非常大。約。 64,000行應該這樣做。我試過這個代碼沒有成功:在mysql中創建一個「數字表」

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 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'CONSTRAINT XPKnumbers PRIMARY KEY CLUSTERED (number)) INSERT INTO n' at line 3

任何人有任何建議,使這項工作?

+0

添加的'插入「值」部分表(列)值(值) – 2012-03-17 15:50:25

回答

18

你缺少分號,逗號,甚至之後更正語法它仍然不是一個好主意,從表中選擇最高每隻需要在循環中插入一行。從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 
+0

哇,現在這正是我正在尋找的。我不明白代碼,但我明白它的工作原理。非常感謝! – user1262890 2012-03-17 18:42:33

+0

好吧,這讓我瘋狂。這段代碼正是我所需要的。它適用於phpmyadmin和navicat,但是當我將它帶入Dreamweaver的sql編輯器時,它告訴我存在mysql錯誤。當我離開查詢代碼(儘管出現錯誤)並嘗試測試網頁時,頁面將返回: 您的SQL語法錯誤;檢查與您的MySQL服務器版本相對應的手冊,以便在'CREATE OR REPLACE VIEW generator_256 AS SELECT((hi.n << 4)| lo.n)第1行的AS n'附近使用正確的語法。 我是什麼做錯了? – user1262890 2012-03-18 13:53:24

+0

當我嘗試運行查詢以將行插入到phpmyadmin中的數字表中時(我無法適應評論框中的所有代碼),我得到: #1064 - 您的SQL語法錯誤;檢查與您的MySQL服務器版本相對應的手冊,以找到正確的語法,以便在'CREATE OR REPLACE VIEW generator_256 AS SELECT((hi.n < < 4)| lo.n)AS n'在第9行使用 – user1262890 2012-03-18 14:05:29

0

你缺少列和約束的聲明之間用逗號:

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