【问题标题】:Delete first X rows of MySQL table once the number of rows is greater than N一旦行数大于 N,就删除 MySQL 表的前 X 行
【发布时间】:2013-07-08 14:05:24
【问题描述】:

我在 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 表结束,我在这里缺少什么?

谢谢。

【问题讨论】:

  • 你确定wordcount = cursor.execute("select * from word")返回记录数?
  • 在python环境下是,在MySQL下不行。例如 wordcount = cursor.execute("select count(*) from word") 在 python 中会返回 1,因为它是 1 行。而我的 SQL 将返回行数(在 python 环境中),即计数
  • 你读过cursordoc吗?
  • 是的。我最想知道为什么我的 sql 删除整个表而不是前 100000 行
  • 在此处查找获取行数的示例:stackoverflow.com/questions/2511679/…

标签: python mysql sql


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    如果您的表“单词”有 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 上建立一些索引,以加快查询速度。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-28
      • 1970-01-01
      • 1970-01-01
      • 2022-08-18
      • 2020-01-27
      相关资源
      最近更新 更多