表:DROP TABLE IF EXISTS `active`;
CREATE TABLE IF NOT EXISTS `active` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `userid` int(10) unsigned NOT NULL,
  `lastactive` int(10) unsigned NOT NULL,
  PRIMARY KEY (`id`),
  KEY `lastactive` (`lastactive`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;插入数据:insert into active values
(null,10000, unix_timestamp("2012-08-20 15:10:02")),
(null,10001, unix_timestamp("2012-08-20 15:10:02")),
(null,10002, unix_timestamp("2012-08-20 15:10:03")),
(null,10003, unix_timestamp("2012-08-20 15:10:03")),
(null,10004, unix_timestamp("2012-08-20 15:10:03")),
(null,10005, unix_timestamp("2012-08-20 15:10:04")),
(null,10006, unix_timestamp("2012-08-20 15:10:04")),
(null,10007, unix_timestamp("2012-08-20 15:10:05")),
(null,10008, unix_timestamp("2012-08-20 15:10:06"))
explain
select * from active where lastactive > unix_timestamp()-3;上面这句索引起作用。
但是我在测试中,因为插入的日期与我测试的当前日期相差不少时间。所以我改写为以下内容:explain
select * from active where lastactive > unix_timestamp("2012-08-20 15:10:06") - 3;但是数据显示,TYPE为ALL,key为NULL。也就是说索引不起作用。我在改写以下语句测试:explain
select * from active where lastactive > unix_timestamp("2012-08-20 15:10:06");上面这个语句,索引又起作用了。请了解这块内容的朋友帮忙解惑~万分感谢。

解决方案 »

  1.   

    mysql认为走索引的代价比不用索引代价大你可以看下unix_timestamp("2012-08-20 15:10:06") - 3;
    unix_timestamp("2012-08-20 15:10:06") - 2;
    unix_timestamp("2012-08-20 15:10:06") - 1;
    unix_timestamp("2012-08-20 15:10:06") - 0;
    unix_timestamp("2012-08-20 15:10:06") + 1 ;
      

  2.   

    说的好像在理。我测试也是如此。减法都是不走索引。加法走索引。这有什么规律吗?还是mysql自动进行的优化?我以为数据太少,在加了几十条数据,仍是这个结果。如果有1000条数据,难道仍是减法不走索引,加法走索引?
      

  3.   

    当MYSQL认为符合条件的记录在30%以上,它就不会再使用索引。
      

  4.   

    mysql符合条件30%记录就会不走索引的。
      

  5.   

    经过测试,在总记录12016条记录的表中,查询小于1854条记录时走索引,大于该记录时不走索引。符合条件的记录在15.4%。为什么不是30%呢?explain
    select * from 表名 where intTime > unix_timestamp() - 24*3600*5-44559;
    intTime为索引。24*3600*5-44559这个我是调试用的。结果是超过1854条记录就不走索引了。而进行全表扫描。这个做怎么解释?
      

  6.   

    是MYSQL认为记录是30%以上,而不是实际MYSQL去查完再决定的。都查完了,还用什么索引啊?!MYSQL会先估算,然后决定是否使用索引。