从数据库表中删除具有多个重复列的行

时间:2012-04-15 09:03:47

标签: mysql sql

我想删除最后一行,因为userid和friendwith列是重复的。

friendshipid    userid  friendwith  friendshipstatus
183             24      102          4
151             24      52           2
155             24      66           2
179             24      66           2

感谢。

3 个答案:

答案 0 :(得分:3)

如果你想保留最新的友谊ID,那就做这样的事情

CREATE TABLE temp_table AS (SELECT * FROM table);
DELETE FROM table WHERE friendshipid NOT IN (SELECT friendshipid FROM (SELECT * FROM temp_table ORDER BY friendshipid DESC) as temp_table GROUP BY userid, friendwith);
DROP TABLE temp_table ;

或者,如果你想保留最早的友谊id,那就做这样的事情

CREATE TABLE temp_table AS (SELECT * FROM table);
DELETE FROM table WHERE friendshipid NOT IN (SELECT friendshipid FROM (SELECT * FROM temp_table ORDER BY friendshipid ASC) as temp_table GROUP BY userid, friendwith);
DROP TABLE temp_table ;

答案 1 :(得分:1)

您可以使用相同的useridfriendswith删除存在另一行的所有行,但可以删除较低的friendshipid。例如:

delete  dup
from    YourTable as dup
join    YourTable orig
on      orig.userid = dup.userid
        and orig.friendwith = dup.friendwith
        and orig.friendshipid < dup.friendshipid

Example at SQL Fiddle.

答案 2 :(得分:0)

select friendshipid  ,  userid  , friendwith  , friendshipstatus from table 
group by userid , friendwith