当MySQL表的行数大于N时,删除前X行

2024-04-23 22:11:02 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

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

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

^{pr2}$

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

但是,这个SQL在删除我的整个表时结束了,我在这里遗漏了什么?在

谢谢。在


Tags: fromexecute环境mysqldeleteselectwordcountcursor
2条回答

如果您的表“word”有ID字段(key auto_increment field),您可以编写一些删除前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字段上建立一些索引,以加快查询速度。在

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

你的delete语句看起来不错,也许你有显式的事务处理?在这种情况下,您必须在删除之后调用db对象上的commit()。在

相关问题 更多 >