php - MySQL删除重复的反向值

标签 php mysql myisam duplicate-removal

我有 MySQL MyISAM 表:

同 table 好友(id, friend_id):

1, 5

5, 1

2, 6

6, 2

3、7

如何删除反向记录?如果记录值 «1, 5» 存在值为 «5, 1» 的记录,我需要删除 «5, 1»。

感谢您的帮助!

最佳答案

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

idfriend_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's being close,在不考虑 tmp 表创建时间的情况下甚至更快。但是,当字段被索引时,创建 tmp 表所需的额外时间会增加)<

关于php - MySQL删除重复的反向值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5438764/

相关文章:

php - 删除括号(以及里面的任何括号)的正则表达式模式

PHP preg_match 匹配

mysql - 数据透视表以外的其他方式 - 增量

PHP PDO 与 BindValue

php - 遍历 PHP 对象

mysql - ALTER TABLE table_name ENGINE=/mysql_convert_table_format 哪个更好

php - 使用 UNION 时结果如何在两个表之间混合

php - Laravel 4 如何使用 ajax 和 json 返回多个 View 数据?

mysql - 同时使用 MyIsam 和 Innodb

MySQL MyISAM 表 - 是否可以仅复制 .MYD、.MYI 和 .FRM 文件进行备份?