1500字范文,内容丰富有趣,写作好帮手!
1500字范文 > SQL 删除重复数据 重复数据只保留ID最小的行

SQL 删除重复数据 重复数据只保留ID最小的行

时间:2023-03-31 11:01:57

相关推荐

SQL 删除重复数据 重复数据只保留ID最小的行

删除重复数据,重复数据只保留ID最小的行

DELETEFROMt_customer_commentWHEREid IN (SELECT*FROM(SELECTidFROMt_customer_commentWHEREremaintain_order_id IN (SELECTremaintain_order_idFROMt_customer_commentGROUP BYremaintain_order_idHAVINGcount(remaintain_order_id) > 1ORDER BYcount(remaintain_order_id) DESC)AND id NOT IN (SELECTmin(id)FROMt_customer_comment tGROUP BYremaintain_order_idHAVINGcount(remaintain_order_id) > 1ORDER BYmin(id) ASC)) AS ttt)

思路:

1:使用 group by ... having 查找出重复的记录 a

2:使用select min(id) group by ...having count(...)>1找出重复数据中id最小的记录 b

3:找出 in a and not in b的数据行,即为需要删除的数据c;

4:直接使用delete from c 在非ORACEL下会报错:[Err] 1093 - You can't specify target table 't_customer_comment' for update in FROM clause;此时需要在c的外边套一层 select * from c as d

5:然后 delete from d ;删除成功!

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。