我有一个如下的SQL查询
select *
from incidents
where remote_ip = '192.168.1.1' and is_infringement = 1
order by reported_at desc
limit 1;
目前这个查询需要运行 313.24 秒。
如果我移除 order by
,那么查询变成了:
select *
from incidents
where remote_ip = '192.168.1.1' and is_infringement = 1
那么,运行只需要0.117秒。
reported_at列已被索引。
所以,有两个问题。首先,为什么使用order_by语句会花费这么长时间?其次,如何加快速度?
编辑:回答下面的问题,以下是使用explain时的输出:
'1','SIMPLE','incidents','index','uniqueReportIndex,idx_incidents_remote_ip','incidentsReportedAt','4',NULL,'1044','100.00','Using where'
表创建语句如下:
CREATE TABLE `incidents` (
`id` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
`incident_ip_id` int(10) unsigned DEFAULT NULL,
`remote_id` bigint(20) DEFAULT NULL,
`remote_ip` char(32) NOT NULL,
`is_infringement` tinyint(1) NOT NULL DEFAULT '0',
`messageBody` text,
`reported_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00' COMMENT 'Formerly : created_datetime',
`created_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
`updated_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
PRIMARY KEY (`id`),
UNIQUE KEY `uniqueReportIndex` (`remote_ip`,`host_id_1`,`licence_feature`,`app_end`),
UNIQUE KEY `uniqueRemoteIncidentId` (`remote_id`),
KEY `incident_ip_id` (`incident_ip_id`),
KEY `id` (`id`),
KEY `incidentsReportedAt` (`reported_at`),
KEY `idx_incidents_remote_ip` (`remote_ip`)
)
注意:我省略了一些与主题无关的字段,所以索引比字段多,但是您可以安全地假设所有索引的字段都在表中。
EXPLAIN
并将输出放入问题中。同时,也请提供表结构(即CREATE TABLE
语句)。 - axiaclimit
子句?你可以在不到1秒的时间内检索所有记录吗?有多少条记录? - Cristian Lupascu