为什么小弟我这句SQL代码,索引不起作用

为什么我这句SQL代码,索引不起作用。

表:

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”);

上面这个语句,索引又起作用了。

请了解这块内容的朋友帮忙解惑~万分感谢。



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 ;




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

为什么小弟我这句SQL代码,索引不起作用

相关文章:

你感兴趣的文章:

标签云: