0

我有一个只有一个 ID 的表(INT auto_increment)。在给定参数之前用条目填充该表的最有效方法是什么?

这是我想出的一个存储过程,但它需要相当长的时间才能用 100000 条记录填充它:

DELIMITER $$
CREATE PROCEDURE insert_id(
IN createnum INT
)
BEGIN
  DECLARE i INT DEFAULT 1;

  WHILE i < createnum DO
    INSERT INTO table VALUES (i);
    SET i = i + 1;
  END WHILE;
END$$
DELIMITER ;
4

1 回答 1

0

最快的方法是不使用任何循环,只使用纯 SQL

insert into table1 (id)
select a.N + b.N * 10 + c.N * 100 + d.N * 1000 + e.N * 10000 + 1 as N
from (select 0 as 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) a
      , (select 0 as 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) b
      , (select 0 as 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) c
      , (select 0 as 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) d
      , (select 0 as 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) e
order by N

此查询插入 100000 行

这是SQLFiddle演示


如果需要,您可以将其包装在一个过程中

CREATE PROCEDURE insert_id(IN _maxid INT)
insert into table1(id)
select n
  from
(
  select a.N + b.N * 10 + c.N * 100 + d.N * 1000 + e.N * 10000 + f.N * 100000 + 1 N
    from (select 0 as 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) a
      , (select 0 as 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) b
      , (select 0 as 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) c
      , (select 0 as 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) d
      , (select 0 as 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) e
      , (select 0 as 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) f
) t
 where n <= _maxid;

此过程最多可填充 1m 行。

示例用法:

CALL insert_id(5500);
CALL insert_id(100000);

您还可以查看这篇文章MySQL:在存储过程中有效地填充表

于 2013-11-05T05:48:48.387 回答