虽然我使用索引Mysql查询仍然工作缓慢

时间:2015-01-06 07:57:15

标签: mysql

背景:

 database engine : innodb
    Table a : size:800 000
                column : createDate ,isNomal ,webid …………………………                  
                index :(createDate ,isNomal ,webid),(webid)

Mysql语句:

  select count(*) from a h
    where h.createDate BETWEEN '2014-6-1 00:00:00' and '2014-12-1 00:00:00'
    and h.isNomal = 1
    and h.webid = '45334';

查询说明:

id select_type table type possible_keys                    key                key_len  ref    rows Extra
1  SIMPLE        h    ref  FKA3978DBEFB528A46,createDate  FKA3978DBEFB528A46  98      const  3184 using where

显示查询的个人资料:

preparing    2.13-5
executinf    2E-6
Sending data 3.3812
end          5E-6
query end    2E-6

mysql-slow-query-log:

\MySQL\MySQL Server 5.1\bin\mysqld, Version: 5.1.62-community-log
(MySQL Community Server (GPL)). started with:
TCP Port: 3306, Named Pipe: (null)
Time                 Id Command    Argument
# Time: 150106 12:33:04
# User@Host: root[root] @ localhost [127.0.0.1]
# Query_time: 3.381193  Lock_time: 0.000000 Rows_sent: 1  Rows_examined: 3300
use baaa;
SET timestamp=1420518784;
select count(*)
from htmlloadtime h
where h.createDate BETWEEN '2014-6-1 00:00:00' and '2014-12-1 00:00:00'
and h.isNomal = 1
and h.websiteConfigInfo_id = '45334';

Myquestion:     这个查询花费3.3秒,对我来说太长了,我想在1秒内完成它,当然,速度越快越好。我应该怎么做 ?谢谢!


删除列webid上的索引

DDL:

CREATE TABLE `a` (
  `id` varchar(32) NOT NULL,
  `createDate` datetime DEFAULT NULL,
  `modifyDate` datetime DEFAULT NULL,
  `isNomal` int(11) NOT NULL,
  `hhhh` double DEFAULT NULL,
  `webid` varchar(32) NOT NULL,
  `aaa` varchar(32) DEFAULT NULL,
  `createDate_date` int(11) DEFAULT NULL,
  `createDate_hour` int(11) DEFAULT NULL,
  `createDate_minute` int(11) DEFAULT NULL,
  `createDate_month` int(11) DEFAULT NULL,
  `createDate_second` int(11) DEFAULT NULL,
  `createDate_year` int(11) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `FKA3978DBE3D0AA64E` (`aaa`) USING BTREE,
  KEY `createDate` (`createDate`,`isNomal`,`webid`) USING BTREE,
  CONSTRAINT `a_ibfk_1` FOREIGN KEY (`aaa`) REFERENCES `aaac` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

Mysql声明:

 select count(*) from a h
    where h.createDate BETWEEN '2014-6-1 00:00:00' and '2014-12-1 00:00:00'
    and h.isNomal = 1
    and h.webid = '45334';

EXPLAIN:

id select_type table type possible_keys   key      key_len  ref   rows    Extra
1  SIMPLE        h    range  createDate  createDate  111      null  399486  using where;using index

1 个答案:

答案 0 :(得分:0)

对于给定的查询,索引必须是

(webid, isNomal, createDate)

按此特定顺序。

主要区别在于用于范围类型比较的列必须是最后一列。由于在应用最后一次比较后,不能再使用其他列。

对于您当前的查询,它是使用h.webid上的单个列索引,这会导致mysql首先 - 在索引中查找相应的行(约3300个),然后执行其他谓词检查实际数据行。