如何在MySQL中加速DateTime比较查询?

时间:2013-10-29 20:23:54

标签: mysql datetime indexing comparison

我在具有大约一百万条记录(~350MB)的MySQL表上执行以下查询。每次大约需要1.5秒。如果我删除OR last_updated > last_geocoded比较,查询时间会提高一个数量级,小于100毫秒。如果我删除last_geocoded = 0行,则查询时间大约为1.5秒。

SELECT id, company_id, raw_address
FROM locations
WHERE
    raw_address IS NOT NULL
    AND (
        last_geocoded = 0
        OR last_updated > last_geocoded
    )
LIMIT 25

如果我将查询缩减为WHERE last_updated > last_geocoded,则查询时间小于100毫秒。

SELECT id, company_id, raw_address
FROM locations
WHERE last_updated > last_geocoded
LIMIT 25

如何加快原始查询?为什么WHERE语句这么慢地减慢了我的查询?

下面是显示我的键的表格架构:

CREATE TABLE `locations` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `company_id` int(11) unsigned DEFAULT NULL,
  `title` varchar(255) DEFAULT NULL,
  `description` text,
  `raw_address` varchar(255) DEFAULT NULL,
  `street` varchar(255) DEFAULT NULL,
  `city` varchar(255) DEFAULT NULL,
  `city_code` varchar(255) DEFAULT NULL,
  `county` varchar(255) DEFAULT NULL,
  `county_code` varchar(255) DEFAULT NULL,
  `state` varchar(255) DEFAULT NULL,
  `state_code` varchar(255) DEFAULT NULL,
  `country` varchar(255) DEFAULT NULL,
  `country_code` varchar(255) DEFAULT NULL,
  `constituency` varchar(255) DEFAULT NULL,
  `constituency_code` varchar(255) DEFAULT NULL,
  `postal_code` int(5) unsigned zerofill DEFAULT NULL,
  `lat` float(10,6) DEFAULT NULL,
  `lon` float(10,6) DEFAULT NULL,
  `headquarters` tinyint(1) unsigned DEFAULT NULL,
  `research_and_development` tinyint(1) unsigned DEFAULT NULL,
  `manufacturing` tinyint(1) unsigned DEFAULT NULL,
  `distribution` tinyint(1) unsigned DEFAULT NULL,
  `sales` tinyint(1) unsigned DEFAULT NULL,
  `retail` tinyint(1) unsigned DEFAULT NULL,
  `source_id` int(11) unsigned DEFAULT NULL,
  `last_updated` datetime NOT NULL,
  `last_geocoded` datetime NOT NULL,
  PRIMARY KEY (`id`),
  KEY `company_id` (`company_id`),
  KEY `raw_address` (`raw_address`),
  KEY `last_updated` (`last_updated`),
  KEY `last_geocoded` (`last_geocoded`),
  KEY `city` (`city`),
  KEY `county` (`county`),
  KEY `state` (`state`),
  KEY `country` (`country`),
  KEY `postal_code` (`postal_code`)
) ENGINE=InnoDB AUTO_INCREMENT=997680 DEFAULT CHARSET=latin1;

以下是使用EXPLAIN运行的原始查询:

"id","select_type","table","type","possible_keys","key","key_len","ref","rows","Extra"
1,"SIMPLE","locations","range","raw_address,last_geocoded","raw_address",258,NULL,509543,"Using where"

0 个答案:

没有答案