从postgresql数据库中删除重复项,其中某些字段为null

时间:2016-09-01 10:01:47

标签: sql database postgresql group-by sql-delete

请考虑以下表格:

+----+-------+--------------+
| id | name  |     info     |
+----+-------+--------------+
|  1 | Chris | NULL         |
|  2 | Den   | some info    |
|  3 | Bob   | another info |
|  4 | Bob   | NULL         |
+----+-------+--------------+

我想删除字段name中的所有重复项,但仅删除infoNULL的所有重复项。对于此示例,我只想删除最后一个Bob(id = 4)。

似乎我可以选择它们:

select name from mytable where info is null group by name having count(*) > 1;

但是我无法检查它是否正确,因为添加字段会让我错误:

select id, name from mytable where info is null group by name having count(*) > 1;
  

错误:专栏" mytable.id"必须出现在GROUP BY子句中或者是   在聚合函数中使用LINE 1:选择id,name from   mytable where info是null group ...

感谢。

1 个答案:

答案 0 :(得分:2)

这应该这样做:

delete from mytable 
where info is null
and exists (select *
            from mytable t2 
            where t2.name = mytable.name
              and t2.info is not null)