【问题标题】:Optimize deletion query for duplicate rows in SQLite3?优化 SQLite3 中重复行的删除查询?
【发布时间】:2021-01-30 16:59:49
【问题描述】:

我正在尝试删除表中用户 ID 最高的重复行之一,包含 350 万行。我有大约 1300 行要删除,我目前正在使用以下查询:

delete from Data
where exists (select 1 from Data t2
              where data.code = t2.code and data.issue = t2.issue
                and data.id < t2.id);

查询已运行超过 15 分钟。有什么办法可以优化它以减少花费的时间吗?我正在使用 SQLite 版本 3.22.0。

【问题讨论】:

    标签: sql database performance sqlite


    【解决方案1】:

    通常,删除表中的大量行是低效的。重建表会更快。

    这个想法是选择你想要的行到另一个表中:

    create table temp_data as
        select t.*
        from data t
        where t.id = (select max(t2.id)
                      from data t2
                      where t2.code = t.code and t2.issue = t.issue
                     );
    

    对于此查询,您需要在(code, issue, id) 上建立索引。

    然后当数据被安全地收起并验证后,您可以清空现有表并重新插入:

    delete from data;
    

    确保您已删除表上的所有触发器。您可以在documentation 中了解 SQLite 的“截断”优化。在大多数其他数据库中,您将使用命令truncate table data

    然后,您可以重新插入数据:

    insert into data
        select *
        from temp_data;
    

    【讨论】:

    • 350 万行中有 1300 行并不是很多行。
    猜你喜欢
    • 2022-01-20
    • 1970-01-01
    • 1970-01-01
    • 2021-08-31
    • 1970-01-01
    • 2021-11-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多