MySQL 删除数据会使用索引吗?

MySQL 删除数据会使用索引吗?

mysql 删除数据是否走索引

mysql 中,当需要删除大量数据时,是否采用索引是一个值得关注的问题。本文将探讨以下问题:

如果我想删除满足某些条件的数据,例如 sex=男、city=北京,mysql 索引是否会被使用?

为了回答这个问题,我们需要了解 mysql 删除数据的机制:

  • 索引的使用条件:当要删除的数据量占表数据的 20% 以上时,mysql 才会使用索引。
  • 条件匹配:索引会被用于匹配删除条件。例如,在你的案例中,如果满足 sex=男 和 city=北京 条件的数据量超过表数据的 20%,那么索引 (sex, city) 将会被使用。

实际操作示例:

假设有一张名为 test_del_idx 的表,包含以下字段:id、name、age、sex、work、city,并且有联合索引 (sex, city)。

当要删除满足 sex=女、city=广州 条件的数据时:

explain delete from test_del_idx where sex="女" and city = "广州";

输出信息:

+----+-------------+--------------+------------+------+---------------+------+---------+------+------+----------+-------------+ | id | select_type | table        | partitions | type | possible_keys | key  | key_len | ref  | rows | filtered | extra       | +----+-------------+--------------+------------+------+---------------+------+---------+------+------+----------+-------------+ |  1 | delete      | test_del_idx | null       | all  | idx_sex_city  | null | null    | null | 1602 |   100.00 | using where | +----+-------------+--------------+------------+------+---------------+------+---------+------+------+----------+-------------+

可以看到,mysql 没有使用索引进行删除,因为满足条件的数据量仅占表数据的 37.68%。

当要删除满足 sex=女、city=惠州 条件的数据时:

explain delete from test_del_idx where sex="女" and city = "惠州";

输出信息:

+----+-------------+--------------+------------+-------+---------------+--------------+---------+-------------+------+----------+-------------+ | id | select_type | table        | partitions | type  | possible_keys | key          | key_len | ref         | rows | filtered | Extra       | +----+-------------+--------------+------------+-------+---------------+--------------+---------+-------------+------+----------+-------------+ |  1 | DELETE      | test_del_idx | NULL       | range | idx_sex_city  | idx_sex_city | 773     | const,const |    6 |   100.00 | Using where | +----+-------------+--------------+------------+-------+---------------+--------------+---------+-------------+------+----------+-------------+

可以看到,mysql 使用了索引 进行删除,因为满足条件的数据量仅占表数据的 0.38%。

© 版权声明
THE END
喜欢就支持一下吧
点赞11 分享