【问题标题】:Delete rows in a table that are not affected by update删除表中不受更新影响的行
【发布时间】:2014-12-08 21:57:11
【问题描述】:

我有两张桌子。其中之一是一个临时表,我从一个大的 CSV 文件中复制数据。之后,我使用临时表更新我的另一个表(请参阅此答案:Copy a few of the columns of a csv file into a table)。

当我使用(更新的)CSV 文件(来自 bash 中的 grep 的数据,每次更新增加行数)再次更新我的临时表时,我想删除不受更新影响的行。我可以有一个比包含所有数据的临时表更小的临时表。

首先:最好删除临时表中的所有数据并用整个更新的 CSV 数据填充它,然后更新/插入另一个表。 第二:还是先更新临时表?

所以这是桌子大小的问题。我说的是 500k 行(带有几何列)。

一个例子:

table
1, NULL
2, NULL

temp table
1, hello
2, good morning

CSV
1, hello there
2, good morning
3, good evening

temp table
1, hello there
2, good morning
3, good evening

temp table
1, hello there
3, good evening

所以我的问题是如何使用 CSV 文件更新表、插入新行、更新旧行以及删除不受更新影响的行。

【问题讨论】:

    标签: sql postgresql csv sql-update insert-update


    【解决方案1】:

    我没有太多的 SQL 经验(半年),但也许你会使用 MINUS 子句比较你的表?使用 MINUS 可以获得未更新的行吗? 附言我说的是PL/SQL)

    【讨论】:

    • minus 是 Oracle 运算符。在标准 SQL(和 Postgres)中,这称为except。加。 MINUS 不是 PL/SQL,那是 SQL。
    • 当然,当我说 PL/SQL 时,我的意思是 Oracle SQL(MINUS)
    【解决方案2】:

    所以我的问题是如何使用 CSV 文件更新表、插入新行、更新旧行以及删除不受更新影响的行。

    我看到了两种可能的解决方案:

    1。单独应用更改

    数据通过一系列更新/删除/插入语句应用,如下所示:

    -- get rid of deleted rows
    delete from the_table
    where not exists (select 1
                      from temp_table tt
                      where tt.id = the_table.id);
    
    -- update changed data
    update the_table 
       set ..
    from temp_table src
    where src.id = the_table.id;
    
    
    -- insert new rows
    insert into the_table
    select ..
    from temp_table src
    where not exists (select 1
                      from the_table t2
                      where t2.id = src.id);
    

    如果其他源写入目标表并且您不想覆盖它,这是必需的方法。也许你甚至不想删除“缺失”的行。或者只更新列的子集。

    2。刷新并填表

    如果您从不修改目标表中的数据,并且没有引用该表的外键,我会刷新并填充真实表:

    truncate the_table;
    copy the_table from '/path/to/data.csv' ...;
    

    如果您在单个事务中运行 truncatecopy,则复制性能将提高,因为它最大限度地减少了 WAL 日志记录的数量。

    【讨论】:

      猜你喜欢
      • 2012-02-11
      • 2014-06-22
      • 2019-11-20
      • 2011-06-11
      • 1970-01-01
      • 2017-05-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多