一旦行数大于N,删除MySQL表的前X行

时间:2013-07-08 14:05:24

标签: python mysql sql

我在MySQL中有一个名为word的只插入表。一旦行数超过1000000,我想删除表的前100000行。

我在python中使用mysqldb,所以我有一个全局变量:

wordcount = cursor.execute("select * from word")

将返回python环境中表中的行数。每次插入新行时,我都会将wordcount增加1。然后我检查行数是否大于1000000,如果是,我想删除前100000行:

if wordcount > 1000000:
    cursor.execute("delete from word limit 100000")

我从这个帖子中得到了这个想法: Delete first X lines of a database

但是,这个SQL结束了删除我的ENTIRE表,我在这里缺少什么?

谢谢。

2 个答案:

答案 0 :(得分:0)

我认为这不是获得行数的正确方法。您需要将语句更改为count(*)然后使用MySQLs cursor.fetchone()来获取结果的元组,其中第一个位置(有点像wordcount = cursor.fetchone()[0])将具有正确的行数

你的删除声明看起来是正确的,也许你有明确的交易?在这种情况下,您必须在删除后调用db对象上的commit()

答案 1 :(得分:0)

如果您的表“word”具有ID字段(键auto_increment字段),您可以编写一些删除前100000行的存储过程。存储过程的关键部分是:

drop temporary table if exists tt_ids;
create temporary table tt_ids (id int not null);

insert into tt_ids -- taking first 100000 rows
select id from word
order by ID
limit 100000;

delete w
from word w
join tt_ids ids on w.ID = ids.ID;

drop temporary table if exists tt_ids;

此外,您可以在ID字段上的tt_ids上构建一些索引,以加快查询速度。

相关问题