Postgresql:如何将临时表中的唯一行附加到现有表?

问题描述 投票:0回答:1

基本上,我从表t2复制唯一行,然后删除所有行,最后从临时表t1中插入唯一行。

//copy unique rows to temp table t1
CREATE TEMPORARY TABLE t1 (select distinct on (name) * from t2);

//delete rows from t2
DELETE FROM t2;

//paste the unique rows from temp table
insert into t2(name, age, grade)
select name, age, grade
from t1;

但是,我不确定是否要以这种有效的方式进行?是否有另一个SQL查询可以剥离表,以便仅保留唯一行?还是显示的SQL有意义?

sql postgresql
1个回答
0
投票

您的方法可能是最好的方法-修改表中许多行的查询通常比清空表并重新插入行要慢。

您必须小心。索引为name的代码将更高效。另外,identity / serial列和其他自动分配的列可能需要特别注意。

如果我们假设该表具有唯一的ID,那么您可以执行以下操作:

delete from t1
    where t1.id > (select max(tt1.id)
                   from t1 tt1
                   where tt1.name = t1.name
                  );
© www.soinside.com 2019 - 2024. All rights reserved.