索引1单表优化

背景:

索引需要花时间多练,练习的前提是需要理解explain里面各个字段的意思。

 参考:

mysql索引失效的常见原因和如何用好索引 - 问题大白 - 博客园 (cnblogs.com)

尚硅谷MySQL数据库高级,mysql优化,数据库优化_哔哩哔哩_bilibili

过程:

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


select * from article;
explain select id,author_id from article where category_id = 1 and comments > 1
order by views desc limit 1; 
show index from article;

-- 查看索引
show index from article;
-- 建立索引1
alter table article add index idx_article_ccv(category_id,comments,views);
create index idx_article_ccv on article(category_id,comments,views);

-- 删除索引1
alter table article drop index idx_article_ccv; 
explain select id,author_id from article where category_id = 1 and comments = 1
order by views desc limit 1; 
-- 第二次优化,建立索引2
alter table article add index idx_article_cv(category_id,views);
-- 删除索引2
alter table article drop index idx_article_cv;

猜你喜欢

转载自blog.csdn.net/Elephantpretty/article/details/124607761
今日推荐