
mysql 删除数据时走索引的条件
在一个用户表中有字段 id、name、age、sex、work 和 city,联合索引为 (sex, city)。现在要删除 sex=男、city=北京 的数据,会不会使用联合索引?
回答:
在 mysql 中,当涉及的数据量超过 20% 时,不会使用索引。因此,如果符合条件的数据量超过表总数据量的 20%,则不会走索引。
实践验证:
- 表总数据量:1602 条
-
符合条件(sex, city)条数:
Ztoy网络商铺多用户版下载在原版的基础上做了一下修正:增加1st在线支付功能与论坛用户数据结合,vip也可与论坛相关,增加互动性vip会员的全面修正评论没有提交正文的问题特价商品的调用连接问题删掉了2个木马文件去掉了一个后门补了SQL注入补了一个过滤漏洞浮动价不能删除的问题不能够搜索问题收藏时放入购物车时出错点放入购物车弹出2个窗口修正定单不能删除问题VIP出错问题主题添加问题商家注册页导航连接问题添加了导航FLASH源文
- 女,广州:604 条
- 女,惠州:6 条
执行删除语句的 explain 结果:
-
女,广州:符合条件数据量超过 20%,不会使用索引。
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 | +----+-------------+--------------+------------+------+---------------+------+---------+------+------+----------+-------------+
-
女,惠州:符合条件数据量少于 20%,会使用索引。
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 | +----+-------------+--------------+------------+-------+---------------+--------------+---------+-------------+------+----------+-------------+









