删除花了很长时间! MySQL的

时间:2010-05-21 20:48:43

标签: sql mysql

我这样做:

delete calibration_2009 from
calibration_2009 join batchinfo_2009
on calibration_2009.rowid = batchinfo_2009.rowid
where batchinfo_2009.reporttime like '%2010%';

两个表都有大约500k行数据 我怀疑250k符合要删除的标准

到目前为止它已经运行了2个小时!有什么问题吗?

dev.mysql.com说我应该这样做:

If you are deleting many rows from a large table, you may exceed the lock table size for an InnoDB table. To avoid this problem, or simply to minimize the time that the table remains locked, the following strategy (which does not use DELETE at all) might be helpful:

Select the rows not to be deleted into an empty table that has the same structure as the original table:

INSERT INTO t_copy SELECT * FROM t WHERE ... ;
Use RENAME TABLE to atomically move the original table out of the way and rename the copy to the original name:

RENAME TABLE t TO t_old, t_copy TO t;
Drop the original table:

DROP TABLE t_old;

我如何用我当前的陈述做到这一点?

4 个答案:

答案 0 :(得分:2)

有些事情要考虑并尝试:

  • 您确定rowid是您的主键吗?
  • 它们是相同的数据类型吗?
  • 你有一个索引构建吗?
  • 在事务中包装删除
  • 确认删除时没有任何有效触发器。

  • 您可以发布表架构吗?

  • 此外,通过Query Analyser运行查询以确认连接正确发生

脚本复制表:

INSERT INTO calibration_2009_copy
SELECT calibration_2009.* 
FROM calibration_2009 
 JOIN batchinfo_2009 
   ON calibration_2009.rowid = batchinfo_2009.rowid
WHERE batchinfo_2009.reporttime not like '%2010%';

RENAME TABLE calibration_2009 TO calibration_2009_old;
RENAME TABLE calibration_2009_copy TO calibration_2009;

DROP TABLE calibration_2009_old;

答案 1 :(得分:1)

尝试为batchinfo_2009.reporttime和rowid添加index 如果使用MyISAM

,还要查看是否有任何表锁

答案 2 :(得分:0)

我不知道mysql,但这个'%2010%'可以保证在SQl Server中进行表扫描。那肯定会让事情变慢。

答案 3 :(得分:0)

WHERE batchinfo_2009.reporttime NOT LIKE '%2010%';

这可能是查询速度太慢的原因。使用LIKE,尤其是字符串开头的通配符,将导致查询不使用reporttime上的索引。

更好的查询是:

DELETE calibration_2009
FROM calibration_2009
JOIN batchinfo_2009
ON calibration_2009.rowid = batchinfo_2009.rowid
WHERE batchinfo_2009.reporttime NOT BETWEEN MAKE_DATE(2010, 1) AND MAKE_DATE(2010, 365);
#`repporttime` is a TIMESTAMP

这将使用索引在repporttime上执行范围扫描。