如何限制一次插入INSERT INTO的记录数

时间:2012-04-03 21:57:00

标签: mysql mysql5

我想像这样插入我的数据库。但表中可能有200k +记录。我想将插入分成10,000个左右的组,我怎样才能在MySQL中有效地执行此操作?

INSERT INTO `slugs` (`sku`, `tablename`)
select `SKU`, 'tableA'
from `tableA`
WHERE `SKU` NOT IN
(select `sku` from `slugs` where `tablename` = 'tableA');

示例代码:http://sqlfiddle.com/#!2/a75a1/8

2 个答案:

答案 0 :(得分:1)

在末尾添加LIMIT 10000并运行它,直到插入行= 0。

如果不是一次性,你可以在一个带循环的程序中这样做。

答案 1 :(得分:0)

试试这个:

SET @rank=0;
select rank
, IF(MOD(rank,10000)=0,CONCAT(IF(MOD(rank,10000)=1,CONCAT("insert ignore into table values (""",NAME,""",""",SKU,""")"),CONCAT(",(""",NAME,""",""",SKU,""")")),";"),IF(MOD(rank,10000)=1,CONCAT("insert ignore into table values (""",NAME,""",""",SKU,""")"),CONCAT(",(""",NAME,""",""",SKU,""")"))) as insert_statement
from (
SELECT @rank:=@rank+1 AS rank,NAME,SKU
from tablea 
) der