建立表:code
CREATE TABLE 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, VIEW 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. VIEW, omments, title, content )VALUES (1, 1, 1, 1, '1', '1'), (2, 2, 2, 2, '2', '2'), (1,1,3,3,'3','3');
建立索引:索引
create index idx_articl_ccv on article(category_id,comments,view);
分析:
查詢和排序字段正好符合索引--> 用到索引rem
explain select id,author_id from article where category_id = 1 and comments =1 order by view desc limit 1;
交換順序--> 依舊使用到了索引it
去除中間的條件--> 依舊使用了索引:select
explain select id,author_id from article where category_id = 1 order by view desc limit 1;
去除開頭條件--> 沒有使用索引了:im
explain select id,author_id from article where comments =1 order by view desc limit 1;
總結:總結
因此在複合索引中,索引第一位的column很重要,只要查詢語句包含了複合索引的第一個條件,基本上就會使用到該複合索引(可能會使用其餘索引)。咱們在建符合索引的時候應該按照column的重要性從左往右建。數據