请考虑以下表格:
+----+-------+--------------+
| id | name | info |
+----+-------+--------------+
| 1 | Chris | NULL |
| 2 | Den | some info |
| 3 | Bob | another info |
| 4 | Bob | NULL |
+----+-------+--------------+
我想删除字段name
中的所有重复项,但仅删除info
为NULL
的所有重复项。对于此示例,我只想删除最后一个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 ...
感谢。
答案 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)