Removing bidirectional duplicates in MySQL

冷暖自知 提交于 2019-12-08 09:41:47

问题


I'm modifying phpBB's table to have bidirectional relationships for friends. Unfortuntately, people that have already added friends have created duplicate rows:

user1   user2   friend
2       3       true
3       2       true
2       4       true

So I'd like to remove rows 1 and 2 from the example above. Currently, this is my query built (doesn't work atm):

DELETE FROM friends WHERE user1 IN (SELECT user1 FROM (SELECT f1.user1 FROM friends f1, friends f2 WHERE f1.user1=f2.user2 AND f1.user2=f2.user1 GROUP BY f1.user1) AS vtable);

inspired by Mysql Duplicate Rows ( Duplicate detected using 2 columns ), but the difference is that I don't have the unique ID column and I'd like stay away from having an extra column.


回答1:


Apologies if this isn't 100% legal MySQL, I'm a MSSQL user...

DELETE F1
FROM friends F1
INNER JOIN friends F2
ON F2.user1 = F1.user2
AND F2.user2 = F1.user1
WHERE F1.user1 < F1.user2



回答2:


DELETE r
FROM friends l, friends r
WHERE l.user1 = r.user2
AND l.user2 = r.user1

This deletes both entries. If you like to keep on of them you have to add a where statement like Will A alread proposed, but i suggest you to use > instead of < to keep the smaller user1 id. Just looks better :)



来源:https://stackoverflow.com/questions/3534034/removing-bidirectional-duplicates-in-mysql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!