【问题标题】:Optimizing a MySQL DELETE Query which is blocking the database优化阻塞数据库的 MySQL DELETE 查询
【发布时间】:2015-03-06 16:24:03
【问题描述】:

我需要一个优化以下 mysql 删除查询的建议:

$group_id = '1234';

     // DELETE GROUP DISCUSSION POSTS 
        mysql_query("DELETE FROM table_groupposts 
                     WHERE grouppost_grouptopic_id 
                     IN (SELECT grouptopic_id from table_grouptopics 
                         WHERE grouptopic_group_id='{$group_id}')
                    ");

echo "DEL groupposts: " . mysql_affected_rows() . "<br />";

拥有大型数据库,运行查询最多需要 70 秒,即使没有讨论帖子。

有什么想法可以加快这个过程吗?

【问题讨论】:

  • 既然你已经用 InnoDB 标记了这个 - 在相关表上放置一个外键索引,并具有适当的关系和 ON DELETE CASCADE 限制;然后只需DELETE FROM table_grouptopics WHERE table_grouptopics.grouptopic_group_id = ?(使用准备好的语句替换? 占位符)并允许数据库处理级联删除。
  • @CD001 老实说,我刚刚切换到 innoDB 并且对此仍然很陌生(“放置外键索引”)。

标签: php mysql innodb sql-delete


【解决方案1】:

为什么不使用 join 进行删除操作而不是子查询

delete tg from table_groupposts tg
join table_grouptopics gt on gt.grouptopic_id = tg.grouppost_grouptopic_id
where gt.grouptopic_group_id='$group_id'

确保连接键被编入索引,如果没有被索引

alter table table_groupposts add index grouppost_grouptopic_id_idx(grouppost_grouptopic_id);

alter table table_grouptopics add index grouptopic_id_idx(grouptopic_id);

最后

alter table table_grouptopics add index grouptopic_group_id_idx(grouptopic_group_id)

【讨论】:

  • 如果我之前不添加索引,它仍然可以使用连接吗?当我理解正确时,添加索引只是为了加快速度,对吧?
  • 是的,索引会加速。对于较小的数据集您不会意识到它,但是当有较大的数据集时,在连接条件上使用索引会加快操作。并在 where 条件下向列添加索引将为查询提供额外的提升。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-01-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多