
mysql 删除数据是否走索引
在 mysql 中,当需要删除大量数据时,是否采用索引是一个值得关注的问题。本文将探讨以下问题:
如果我想删除满足某些条件的数据,例如 sex=男、city=北京,mysql 索引是否会被使用?
为了回答这个问题,我们需要了解 mysql 删除数据的机制:
实际操作示例:
假设有一张名为 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%。
以上就是MySQL 删除数据会使用索引吗?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号