在大型数据库MySQL中多次搜索的最有效方法是什么

时间:2013-05-20 09:05:13

标签: mysql performance large-data bigdata

我有GEO ip location数据库,其中每个国家都有一系列与之相关的IP。

country | ip_start | ip_end

我有一个非常大的ip列表(100万),我需要通过查找geo_database将每个ip关联到正确的国家。

我目前使用这种效率低下的查询(Python btw):

"SELECT * FROM geoipv4_country WHERE %s BETWEEN start_integer AND end_integer" % myDict[ipnum]"

正如你所看到的那样,对于我的列表中的每个ip都会这样做,这需要花费大量的时间,因为对于每个ip我需要查询数据库。

这样做有效吗?

提前谢谢

1 个答案:

答案 0 :(得分:1)

首先,创建一个包含大量IP地址列表的表:

CREATE TABLE ip_list (
    ipnum INTEGER
);
INSERT INTO ip_list (ipnum) VALUES
    (<ip1>), (<ip2>), (<ip3>), (<ip4>), ..., (<ipN>);

然后,您可以使用以下查询获取列表:

SELECT i.ipnum, c.country
FROM geoipv4_country с,
     ip_list         i
WHERE i.ipnum BETWEEN c.start_integer
                  AND c.end_integer

这假设geoipv4_country表中的范围不能重叠。

为了提高效率,请务必至少拥有以下索引:

CREATE INDEX c1 ON geoipv4_country(start_integer);
CREATE INDEX c2 ON geoipv4_country(end_integer);
相关问题