I have this query:
SELECT `country`
FROM `geoip_base`
WHERE 1840344811 BETWEEN `start` AND `stop`
It’s badly use index (use, but parse big part of table) and work too slowly.
I tried use ORDER BY and LIMIT, but it hasn’t helped.
“start <= 1840344811 AND 1840344811 <= stop” works similar.
CREATE TABLE IF NOT EXISTS `geoip_base` (
`start` decimal(10,0) NOT NULL,
`stop` decimal(10,0) NOT NULL,
`inetnum` char(33) collate utf8_bin NOT NULL,
`country` char(2) collate utf8_bin NOT NULL,
`city_id` int(11) NOT NULL,
PRIMARY KEY (`start`,`stop`),
UNIQUE KEY `start` (`start`),
UNIQUE KEY `stop` (`stop`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
Table have 57,424 rows.
Explain for query “… BETWEEN START AND STOP ORDER BY START LIMIT 1”:
using key stop and get 24099 rows.
Without order and limit, mysql doesn’t use keys and gets all rows.
If your table is
MyISAM, you can improve this query usingSPATIALindexes:This article may be of interest to you:
Alternatively, if your ranges do not intersect (and from the nature of the database I except they don’t), you can create a
UNIQUEindex ongeoip_base.startand use this query:Note the
ORDER BYandLIMITconditions, they are important.This query is similar to this:
Using
ORDER BY / LIMITmakes the query to choose descending index scan onstartwhich will stop on the first match (i. e. on the range with thestartclosest to theIPyou enter). The additional filter on stop will just check whether the range contains thisIP.Since your ranges do not intersect, either this range or no range at all will contain the
IPyou’re after.