MySQL大删除

时间:2018-07-10 08:51:41

标签: mysql

我需要从MySQL的大型INNODB表中删除很多行。

表中有数百万行,此语句可能需要几分钟,甚至几个小时。

我尝试了此存储过程但没有成功,因为循环中的SQL语法错误。

如何从大型表中删除很多行?

   BEGIN
   Set @a = SELECT MIN(sId) FROM doTable;
   LOOP
      SELECT @z := sId FROM doTable WHERE sId >= @a ORDER BY sId LIMIT 1000,1;
      If @z is null
         exit LOOP
      DELETE FROM doTable
         WHERE sId >= @a
           AND sId <  @z
           AND sType IS NULL
      SET @a = @z
      sleep 3
   ENDLOOP
   DELETE FROM doTable
      WHERE sId >= @a
        AND sType IS NULL;
END

2 个答案:

答案 0 :(得分:1)

在MYSQL中尝试此SP:

BEGIN

REPEAT
DELETE FROM yourTable
WHERE yourCondition LIMIT 10000;
UNTIL ROW_COUNT() = 0 END REPEAT;

END

我希望我能帮上忙。

答案 1 :(得分:0)

这是一个有效的示例,添加了睡眠,很不错:

DROP PROCEDURE IF EXISTS clean_someTable;

DELIMITER $$

CREATE PROCEDURE clean_someTable()

BEGIN   
    REPEAT
        DO SLEEP(1);
        DELETE FROM someTable 
        WHERE (created_at < NOW() - INTERVAL 1 MONTH) 
        ORDER BY primary_key_id 
        LIMIT 10000;        
    UNTIL ROW_COUNT() = 0 END REPEAT;
END$$

DELIMITER ;

CALL clean_someTable();