首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 数据库 > Mysql >

这个查询为什么没有使用索引?该如何处理

2012-06-14 
这个查询为什么没有使用索引?表结构:SQL codeCreate Table: CREATE TABLE `sina_weibo_status` (`sid` big

这个查询为什么没有使用索引?
表结构:

SQL code
Create Table: CREATE TABLE `sina_weibo_status` (  `sid` bigint(20) NOT NULL DEFAULT '0',  `text` varchar(255) DEFAULT NULL,  `source` varchar(255) DEFAULT NULL,  `truncated` int(1) DEFAULT NULL ,  `thumbnail_pic` varchar(255) DEFAULT NULL,  `bmiddle_pic` varchar(255) DEFAULT NULL,  `original_pic` varchar(255) DEFAULT NULL,  `uid` bigint(20) DEFAULT NULL COMMENT,  `retweeted_status` bigint(20) DEFAULT '0',  `in_reply_to_status_id` bigint(20) DEFAULT NULL,  `created_at` datetime DEFAULT NULL,  `aid` int(10) NOT NULL COMMENT,  `category` int(10) NOT NULL,  `status` tinyint(4) NOT NULL DEFAULT '0',  `retweeted_num` int(11) NOT NULL DEFAULT '0',  `rank` double NOT NULL DEFAULT '0',  `created_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,  `updated_date` datetime DEFAULT NULL,  PRIMARY KEY (`sid`),  KEY `sina_weibo_status_category_fk1` (`category`),  KEY `sina_weibo_status_rank_index` (`rank`),  KEY `sina_weibo_status_updated_date_index` (`updated_date`),  KEY `sina_weibo_status_uid` (`uid`),  KEY `sina_weibo_status_retweeted_status` (`retweeted_status`),  CONSTRAINT `sina_weibo_status_ibfk_1` FOREIGN KEY (`category`) REFERENCES `category` (`id`) ON DELETE NO ACTION) ENGINE=InnoDB DEFAULT CHARSET=utf8

查询语句:
SQL code
mysql> explain SELECT * FROM `sina_weibo_status` `t` WHERE ((category='11') AND (status='0')) AND (retweeted_status='0') ORDER BY rank desc LIMIT 20 \G;*************************** 1. row ***************************           id: 1  select_type: SIMPLE        table: t         type: index_mergepossible_keys: sina_weibo_status_category_fk1,sina_weibo_status_retweeted_status          key: sina_weibo_status_category_fk1,sina_weibo_status_retweeted_status      key_len: 4,9          ref: NULL         rows: 275502        Extra: Using intersect(sina_weibo_status_category_fk1,sina_weibo_status_retweeted_status); Using where; Using filesort


排序没有使用索引,但是rank定义索引了,这是怎么回事?

[解决办法]
你的category、status、retweeted_status有多少种值,在
category、status、retweeted_status、rank上建立复合索引试试
[解决办法]
创建索引如下。

create index xxx on `sina_weibo_status`( category, status, retweeted_status, rank);

另外它也利用了索引,并不是没用。 intersect(sina_weibo_status_category_fk1,sina_weibo_status_retweeted_status);

[解决办法]
lz还没明白索引的工作原理。

你的数据库,每张表好比一个小区(假设有10000人),里面每个人好比一条记录。假设每个人有几十个属性(字段),比如姓名、年龄、性别、身高、体重……

现在要找到所有年龄在20-30岁之间的男性,如果没有索引的话,你就需要挨家挨户,每个人都去拜访一下,每个人都要问一下,“你多大了,男的还是女的”

如果建立了年龄一个字段的索引,那么就好比在派出所有一本小册子,里面按照年龄排序,记录了所有人的信息,这时候,你只要翻一下这个小册子,把20-30岁之间的人都找出来(假设500个人),对于暂时不知道的性别信息,你只要上门访问这500人,找到其中的250人即可。

如果建立了年龄——性别联合索引,即首先根据年龄排序,相同年龄段中按照性别排序,那只要翻翻小册子即可。

至于ORDER BY,那是找出250人后,让他们排队的依据。explain说你没使用索引,那是指你在10000人中找这250人的时候,挨家挨户上门了,没有翻户口本。

[解决办法]
1。 使用了索引,但没有使用RANK索引,这个是由MYSQL根据数据情况进行优化的。

热点排行