我有MySQL MyISAM表:
表朋友(id,friend_id):
1,5
5,1
2,6
6,2
3,7
如何删除反向记录?如果记录值“1,5”存在值为“5,1”的记录,则需要删除“5,1”.
Thanx寻求帮助!
最佳答案
DELETE F1
FROM friends F1,friends F2
WHERE F1.friend_id = F2.id
AND F2.friend_id = F1.id
AND F1.id > F1.friend_id
编辑
一个更好的语法将是:
DELETE F1
FROM friends F1
JOIN friends F2 ON F1.friend_id = F2.id AND F2.friend_id = F1.id
WHERE F1.id > F1.friend_id
但执行时间是一样的.
同样,我已经为快速创建了this small script.脏基准.
结果:
没有索引:
Dalen: 600 => 400 rows. Time: 0.0274 Mark: 600 => 400 rows. Time: 0.4323 Frosty: 600 => 400 rows. Time: 0.4081 Nick: 600 => 400 rows. Time: 0.3201
列id和friend_id的单独索引:
Dalen: 600 => 400 rows. Time: 0.0201 Mark: 600 => 400 rows. Time: 0.0095 Frosty: 600 => 400 rows. Time: 0.0059 Nick: 600 => 400 rows. Time: 0.3257
(id,friend_id)上的唯一索引:
Dalen: 600 => 400 rows. Time: 0.0168 Mark: 600 => 400 rows. Time: 0.0057 Frosty: 600 => 400 rows. Time: 0.0041 Nick: 600 => 400 rows. Time: 0.3209
结论:
> Dalen:当列未编入索引时速度最快
> Frosty:列索引时速度最快(Mark关闭,在“索引情况”中更快,而不考虑tmp表创建时间.但是,当字段被索引时,tmp表创建所需的额外时间会增加)