gpt4 book ai didi

MySQL:查询之间的最佳索引

转载 作者:IT王子 更新时间:2023-10-28 23:46:45 25 4
gpt4 key购买 nike

我有一个结构如下的表:

CREATE TABLE `geo_ip` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`start_ip` int(10) unsigned NOT NULL,
`end_ip` int(10) unsigned NOT NULL,
PRIMARY KEY (`id`),
KEY `start_ip` (`start_ip`),
KEY `end_ip` (`end_ip`),
KEY `start_end` (`start_ip`,`end_ip`),
KEY `end_start` (`end_ip`,`start_ip`)) ENGINE=InnoDB;

MySQL 似乎无法对我的大多数查询使用索引,因为 where 子句使用 between 介于 start_ip 之间> 和 end_ip:

select * from geo_ip where 2393196360 between start_ip and end_ip;

+----+-------------+--------+------+-------------------------------------+------+---------+------+---------+-------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+--------+------+-------------------------------------+------+---------+------+---------+-------------+
| 1 | SIMPLE | geo_ip | ALL | start_ip,end_ip,start_end,end_start | NULL | NULL | NULL | 2291578 | Using where |
+----+-------------+--------+------+-------------------------------------+------+---------+------+---------+-------------+

该表有几百万条记录。我尝试通过删除 start_ipend_ip 列来扩展表格,并为 start_ipend_ip 的每个可能值创建一行 作为 id,然后查询 id。虽然这极大地提高了查询性能,但它导致表大小从不到 1 GB 增长到数十 GB(该表显然还有其他列)。

还可以做些什么来提高查询性能?我可以以某种方式更改查询,还是可以对列进行不同的索引以导致命中?或者可能是我还没有想到的?

编辑:

奇怪的是,索引用于某些值。例如:

explain select * from geo_ip where 3673747503 between start_ip and end_ip;
+----+-------------+--------+-------+-------------------------------------+--------+---------+------+-------+-------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+--------+-------+-------------------------------------+--------+---------+------+-------+-------------+
| 1 | SIMPLE | geo_ip | range | start_ip,end_ip,start_end,end_start | end_ip | 4 | NULL | 19134 | Using where |
+----+-------------+--------+-------+-------------------------------------+--------+---------+------+-------+-------------+

最佳答案

不知道为什么,但是在查询中添加 order by 子句和限制似乎总是会导致索引命中,并且会在几毫秒而不是几秒内执行。

explain select * from geo_ip where 2393196360 between start_ip and end_ip order by start_ip desc limit 1;
+----+-------------+--------+-------+-----------------+----------+---------+------+--------+-------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+--------+-------+-----------------+----------+---------+------+--------+-------------+
| 1 | SIMPLE | geo_ip | range | start_ip,end_ip | start_ip | 4 | NULL | 975222 | Using where |
+----+-------------+--------+-------+-----------------+----------+---------+------+--------+-------------+

这对我来说已经足够好了,尽管我很想知道优化器为什么决定在另一种情况下不使用索引的原因。

关于MySQL:查询之间的最佳索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22125474/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com