索引小試

http://www.jb51.net/article/50103.htm  mysql 悲觀鎖 樂觀鎖mysql

http://blog.csdn.net/xifeijian/article/details/20313977 mysql  鎖sql

建表優化

CREATE TABLE IF NOT EXISTS `article` (`id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`author_id` INT(10) UNSIGNED NOT NULL,
`category_id` INT(10) UNSIGNED NOT NULL,
`views` INT(10) UNSIGNED NOT NULL,
`comments` INT(10) UNSIGNED NOT NULL,
`title` VARBINARY(255) NOT NULL,
`content` TEXT NOT NULL,
PRIMARY KEY (`id`)
);.net

插數據htm

INSERT INTO `article`
(`author_id`, `category_id`, `views`, `comments`, `title`, `content`) VALUES
(1, 1, 1, 1, '1', '1'),
(2, 2, 2, 2, '2', '2'),
(1, 1, 3, 3, '3', '3');blog

建索引排序

ALTER TABLE `article` ADD INDEX X ( `category_id` , `comments`, `views` );
ALTER TABLE `article` ADD INDEX Y ( `category_id` , `views` ) ;索引

ALTER TABLE `article` ADD INDEX Z ( `comments` ) ;get

 

查表it

EXPLAIN
SELECT author_id
FROM `article`
WHERE comments > 1  AND category_id = 1 
ORDER BY views DESC
LIMIT 1

結果

分析

按照 BTree 索引的工做原理,先排序 category_id,若是遇到相同的 category_id 則再排序 comments,若是遇到相同的 comments 則再排序 views。當 comments 字段在聯合索引裏處於中間位置時,因comments > 1 條件是一個範圍值(所謂 range),MySQL 沒法利用索引再對後面的 views 部分進行檢索,即 range 類型查詢字段後面的索引無效

優化:刪除索引X    DROP INDEX X ON article;

執行

EXPLAIN
SELECT author_id
FROM `article`
WHERE comments > 1  AND category_id = 1 
ORDER BY views DESC
LIMIT 1

結果

 

執行

EXPLAIN
SELECT author_id
FROM `article`
WHERE comments > 1
ORDER BY views DESC
LIMIT 1

結果

 

結論 聯合索引中包含 <  > 操做時,索引中的部分會失效,把這部分從索引中去掉。

        當存在多個索引時 包含 < 的索引會被忽略

相關文章
相關標籤/搜索