How to delete all duplicate records from SQL Table?

后端 未结 4 419

Hello I have table name FriendsData that contains duplicate records as shown below

fID UserID  FriendsID       IsSpecial      CreatedBy
---         


        
相关标签:
4条回答
  • 2020-12-30 14:26

    Try this

    DELETE
    FROM FriendsData 
    WHERE fID NOT IN
    (
    SELECT MIN(fID)
    FROM FriendsData 
    GROUP BY UserID, FriendsID)
    

    See here

    Or here is more ways to do what you want

    Hope this helps

    0 讨论(0)
  • 2020-12-30 14:26

    It seems counter-intuitive, but you can delete from a common table expression (under certain circumstances). So, I'd do it like so:

    with cte as (
      select *, 
         row_number() over (partition by userid, friendsid order by fid) as [rn]
      from FriendsData
    )
    delete cte where [rn] <> 1
    

    This will keep the record with the lowest fid. If you want something else, change the order by clause in the over clause.

    If it's an option, put a uniqueness constraint on the table so you don't have to keep doing this. It doesn't help to bail out a boat if you still have a leak!

    0 讨论(0)
  • 2020-12-30 14:28

    I don't know if the syntax is correct for MS-SQL, but in MySQL, the query would look like:

    DELETE FROM FriendsData WHERE fID 
           NOT IN ( SELECT fID FROM FriendsData 
                       GROUP BY UserID, FriendsUserID, IsSpecial, CreatedBy)
    

    In the GROUP BY clause you put the columns you need to be identical in order to consider two records duplicate

    0 讨论(0)
  • 2020-12-30 14:37

    Try this query,

      select * from FriendsData f1, FriendsData f2
      Where f1.fID=f2.fID and f1.UserID  =f2.UserID  and f1.FriendsID  =f2.FriendsID
    

    If it returns you the duplicate rows, then replace Select * by "Delete"

    that will solve your problem

    0 讨论(0)
提交回复
热议问题