我使用的是MySQL 5.5.14版,从500万行的表中运行以下查询:
SELECT P.ID, P.Type, P.Name, P.cty
, X(P.latlng) as 'lat', Y(P.latlng) as 'lng'
, P.cur, P.ak, P.tn, P.St, P.Tm, P.flA, P.ldA, P.flN
, P.lv, P.bd, P.bt, P.nb
, P.ak * E.usD as 'usP'
FROM PIG P
INNER JOIN EEL E
ON E.cur = P.cur
WHERE act='1'
AND flA >= '1615'
AND ldA >= '0'
AND yr >= (YEAR(NOW()) - 100)
AND lv >= '0'
AND bd >= '3'
AND bt >= '2'
AND nb <= '5'
AND cDate >= NOW()
AND MBRContains(LineString( Point(-65.6583, -87.8906)
, Point(65.6583, 87.8906)
), latlng)
AND Type = 'g'
AND tn = 'l'
AND St + Tm - YEAR(NOW()) >= '30'
HAVING usP BETWEEN 300/2 AND 300 LIMIT 100;
表定义是:
CREATE TABLE `PIG` (
`ID` int(10) unsigned NOT NULL AUTO_INCREMENT,
`Email` char(50) NOT NULL,
`Type` char(1) NOT NULL,
`Name` char(25) DEFAULT NULL,
`cty` char(2) DEFAULT NULL,
`latlng` point NOT NULL,
`tn` char(1) NOT NULL DEFAULT 'l',
`St` smallint(4) unsigned NOT NULL DEFAULT '0',
`Tm` smallint(3) unsigned NOT NULL DEFAULT '0',
`yr` smallint(4) unsigned NOT NULL DEFAULT '0',
`flA` mediumint(6) unsigned NOT NULL DEFAULT '0',
`ldA` mediumint(6) unsigned NOT NULL DEFAULT '0',
`flN` smallint(3) unsigned NOT NULL DEFAULT '1',
`lv` smallint(3) unsigned NOT NULL DEFAULT '0',
`bd` tinyint(2) unsigned NOT NULL DEFAULT '0',
`bt` tinyint(2) unsigned NOT NULL DEFAULT '0',
`nb` tinyint(1) unsigned NOT NULL DEFAULT '9',
`cur` char(3) DEFAULT NULL,
`ak` int(10) unsigned NOT NULL DEFAULT '0',
`Des` tinytext,
`pDate` datetime DEFAULT NULL,
`cDate` date DEFAULT NULL,
`act` tinyint(1) unsigned NOT NULL DEFAULT '0',
`bid` tinyint(3) unsigned NOT NULL DEFAULT '0',
`ab` tinyint(3) unsigned NOT NULL DEFAULT '0',
PRIMARY KEY (`ID`),
KEY `id_ca` (`cty`,`ak`),
SPATIAL KEY `id_latlng` (`latlng`)
) ENGINE=MyISAM AUTO_INCREMENT=5000001 DEFAULT CHARSET=latin1
和
CREATE TABLE `EEL` (
`cur` char(3) NOT NULL,
`usD` decimal(11,10) NOT NULL,
PRIMARY KEY (`cur`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1
以下显示了查询执行计划:
*************************** 1. row ***************************
id: 1
select_type: SIMPLE
table: P
type: range
possible_keys: id_latlng
key: id_latlng
key_len: 34
ref: NULL
rows: 742873
Extra: Using where
*************************** 2. row ***************************
id: 1
select_type: SIMPLE
table: E
type: eq_ref
possible_keys: PRIMARY
key: PRIMARY
key_len: 3
ref: BS.P.cur
rows: 1
Extra:
由于存在NOW()函数,此查询不使用查询缓存。从我之前的posting开始,我发现存在其他形式的缓存可以将查询从 300s的初始时间降低到小于2s 。我的问题是:“如何改善上述查询时间,知道缓存不会有多大用处,因为latlng的搜索条件不断变化?”请注意,latlng上的空间索引已经为优化目的而建。
干杯,本
答案 0 :(得分:0)
良好的指数是具有高选择性的指数。您的条件主要是范围条件,这对可以在复合索引中使用的字段构成限制。
要调查的可能索引(由具有等级检查的那些字段组成,最后是一个带范围检查的字段):
(act, Type, tn, flA)
(act, Type, tn, cDate)
(act, Type, tn, nb)
要在不创建索引的情况下检查选择性,可以使用:
SELECT COUNT(*)
FROM PIG P
WHERE act='1'
AND Type = 'g'
AND tn = 'l'
AND flA >= '1615'
和
SELECT COUNT(*)
FROM PIG P
WHERE act='1'
AND Type = 'g'
AND tn = 'l'
AND cDate >= NOW()
和
SELECT COUNT(*)
FROM PIG P
WHERE act='1'
AND Type = 'g'
AND tn = 'l'
AND nb <= '5'
并将输出与空间索引中的742873
进行比较。