正如 user1045047 提到的,Amazon Redshift 不支持唯一约束,因此我一直在寻找使用删除语句从表中删除重复记录的方法。
最后,我找到了一个合理的方法。
Amazon Redshift 支持创建存储自动生成的唯一编号的 IDENTITY 列。
http://docs.aws.amazon.com/redshift/latest/dg/r_CREATE_TABLE_NEW.html
以下sql用于PostgreSQL删除OID为唯一列的重复记录,您可以通过将OID替换为标识列来使用此sql。
DELETE FROM duplicated_table WHERE OID > (
SELECT MIN(OID) FROM duplicated_table d2
WHERE column1 = d2.dupl_column1
AND column2 = d2.column2
);
这是我在 Amazon Redshift 集群上测试的示例。
create table auto_id_table (auto_id int IDENTITY, name varchar, age int);
insert into auto_id_table (name, age) values('John', 18);
insert into auto_id_table (name, age) values('John', 18);
insert into auto_id_table (name, age) values('John', 18);
insert into auto_id_table (name, age) values('John', 18);
insert into auto_id_table (name, age) values('John', 18);
insert into auto_id_table (name, age) values('Bob', 20);
insert into auto_id_table (name, age) values('Bob', 20);
insert into auto_id_table (name, age) values('Matt', 24);
select * from auto_id_table order by auto_id;
auto_id | name | age
---------+------+-----
1 | John | 18
2 | John | 18
3 | John | 18
4 | John | 18
5 | John | 18
6 | Bob | 20
7 | Bob | 20
8 | Matt | 24
(8 rows)
delete from auto_id_table where auto_id > (
select min(auto_id) from auto_id_table d
where auto_id_table.name = d.name
and auto_id_table.age = d.age
);
select * from auto_id_table order by auto_id;
auto_id | name | age
---------+------+-----
1 | John | 18
6 | Bob | 20
8 | Matt | 24
(3 rows)
它也适用于这样的 COPY 命令。
这种方式的优点是您不需要运行 DDL 语句。但是,它不适用于没有标识列的现有表,因为无法将标识列添加到现有表中。删除现有表中重复记录的唯一方法是像这样迁移所有记录。 (与user1045047的回答相同)
insert into temp_table (select distinct from original_table);
drop table original_table;
alter table temp_table rename to original_table;