#建立表格 CREATE TABLE if not exists `article`( `id` int(10) UNSIGNED NOT NULL PRIMARY KEY 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 ); #插入數據 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');
#查詢category_id爲1且comments大於1的狀況下,views最多的article_id SELECT id,author_id FROM article WHERE category_id=1 AND comments>1 ORDER BY views DESC LIMIT 1; #性能分析 explain SELECT id,author_id FROM article WHERE category_id=1 AND comments>1 ORDER BY views DESC LIMIT 1;
結論:type是ALL,Extra裏面還出現了Using filesort,雖然這條語句可以查詢出來結果,可是很消耗行性能,須要優化。mysql
(1)查看索引sql
show index from article;
(2)開始優化性能
方式一:新建索引+刪除索引優化
建立索引spa
create index idx_article_ccv on article(`category_id`,`comments`,`views`);
刪除索引code
drop index idx_article_ccv on article
這裏咱們已經創建了索引,爲何沒有用?blog
這是由於按照BTree的工做原理,首先排序category_id,若是遇到相同的category_id,則在排序comments,若是遇到相同的comments,則再排序view。當comments字段在聯合索引中處於中間位置時,由於comments>1條件是一個範圍值(所謂range),MySQL沒法利用索引再對後面的views部分進行檢索,即range類型查詢字段後面的索引無效。排序
方式二(正確)索引
create index idx_article_cv on article(category_id,views);