Sql 从表中删除重复行
我的表中有唯一的键id键,但我有一个具有重复值的列?我如何在只保留其中一个的情况下去除它们: 重复记录:Sql 从表中删除重复行,sql,postgresql,Sql,Postgresql,我的表中有唯一的键id键,但我有一个具有重复值的列?我如何在只保留其中一个的情况下去除它们: 重复记录: id | name | surname | 1 | test | one | 2 | test | two | 3 | test3 | three | 4 | test7 | four | 5 | test | five | 6 | test11 | eleven | 无重复项: id | name |
id | name | surname |
1 | test | one |
2 | test | two |
3 | test3 | three |
4 | test7 | four |
5 | test | five |
6 | test11 | eleven |
无重复项:
id | name | surname |
1 | test | one |
3 | test3 | three |
4 | test7 | four |
6 | test11 | eleven |
我在谷歌上搜索过这个,但它似乎不起作用:
DELETE ct1
FROM mytable ct1
, mytable ct2
WHERE ct1.name = ct2.name
AND ct1.id < ct2.id
ERROR: syntax error at or near "ct1"
LINE 1: DELETE ct1
^
********** Error **********
删除ct1
来自mytable ct1
,mytable ct2
其中ct1.name=ct2.name
和ct1.id
我正在使用postgres数据库。您可以多次尝试运行该数据库
delete from mytable where id in (
select max(id)
from mytable
group by name
having count(1) > 1
);
其中,多次等于您在name
列中的最大重复次数
否则,您可以尝试此更复杂的查询:
delete from mytable where id in (
select id from mytable
except
(
select min(id)
from mytable
group by name
having count(1) > 1
union all
select min(id)
from mytable
group by name
having count(1) = 1
)
);
只运行一次此查询将删除所有需要的内容。虽然还没有尝试过…使用,但实际上我并不完全确定语法,因为我不太擅长PostgreSQL,这只是一个提示(请任何人更正):
很高兴这有帮助。对于这样复杂的分组,我建议您学习
窗口函数
,例如秩
。@Dalen在其他答案中建议。它们是值得学习的。在清理完数据之后,您可能需要对“name”设置一个唯一的约束。
DELETE FROM mytable
WHERE id NOT IN
(
SELECT x.id FROM
(
SELECT id, RANK() OVER (PARTITION BY name ORDER BY id ASC) AS r
FROM mytable
) x
WHERE x.r = 1
)