假如有这样一张表news:字段:id,title,time,image,author,现在表中有1万多条记录,其中title重复的有上千条。如何才能一次性将title重复记录删除呢?
id | title | time | image | author |
1 | 我是高富帅 | 1234 | pic1.jpg | 1 |
2 | 我是白富美 | 1233 | pic2.jpg | 2 |
3 | 我是高富帅 | 1235 | pic3.jpg | 3 |
本人使用sqlserver数据库。
现在先将所有的重复数据显示出来:
select id,title,time,image,author from news where (title in (select title from news group by title having (count(title) > 1)))
删除多余的记录
delete from news where (title in (select title from news group by title having (count(title) > 1))) and (id not in (select min(id) as nid from news group by title having (count(title) > 1)))
使用min的原因是保留发布时间最早的记录,如果要保留时间最后发布的可以使用max