单表-双表-三表优化

单表优化
建表

create table article(
id int unsigned not null primary key auto_increment,
author_id int unsigned not null,
category_id int unsigned not null,
views int unsigned not null,
comments int unsigned not null,
title varchar(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

表结构:
在这里插入图片描述
执行SQL:查询category_id为1且comments大于1的情况下,views最多的article_id

在这里插入图片描述
分析以上SQL语句
在这里插入图片描述
显示: 无索引 type–ALL(全表扫描) Extra—using filesort(文件内排序) 需要优化

建索引
在这里插入图片描述
在这里插入图片描述
建索引后:using filesort文件内排序仍然存在,发现索引长度是8,一个索引长度是4,说明还有一个索引没有用上,范围之外的comments> 1失效,
在这里插入图片描述删除以上创建的三个索引,重新创建两个新的索引,除开comments。
在这里插入图片描述
优化后:type --ref Extra 已无using filesort
如果只建views索引,type–>index , tpye–> index
ref 优于>index ,建两个索引的最佳。

在这里插入图片描述

双表优化
建表

商品类别
create table class(
id int unsigned not null primary key auto_increment,
card int unsigned not null
);

图书表
create table book(
bookid int unsigned not null auto_increment primary key,
card int unsigned not null
);

– 函数 python random
– mysql rand() 随机小数 floor 返回整数部分
SELECT FLOOR(RAND()*100);
随机插入数据:
INSERT INTO class(card) VALUES(FLOOR(RAND()*100));
INSERT INTO book(card) VALUES(FLOOR(RAND()*100));

连接两表explain分析SQL语句:
在这里插入图片描述
type–>ALL全扫描,出现using join buffer 需要优化
在这里插入图片描述
驱动表的概念,mysql中指定了连接条件时,满足查询条件的记录行数少的表为驱动表;如未指定查询条件,则扫描行数少的为驱动表
mysql优化器就是这么粗暴以小表驱动大表的方式来决定执行顺序的。

例:t1表数据10000条,t2表数据10条 强制t2连接t1,小表驱动大表为优
explain select * from t2 straight_join t1 on t1.a=t2.a;
explain select * from t2 inner_join t1 on t1.a=t2.a;
在这里插入图片描述
三表分析:创建的表未添加索引
在这里插入图片描述
给两个表添加索引:三表优化写两个表优化基本一样
在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值