当前位置:网站首页>【2022黑马程序员】SQL优化
【2022黑马程序员】SQL优化
2022-06-25 06:33:00 【小七rrrrr】
【黑马程序员】SQL优化笔记
文章目录
插入数据优化
如果我们需要一次性往数据库表中插入多条记录,可以从以下三个方面进行优化。
- 批量插入数据
- 手动控制事务
- 主键顺序插入,性能要高于乱序插入
大批量插入数据
如果一次性需要插入大批量数据(比如: 几百万的记录),使用insert语句插入性能较低,此时可以使用MySQL数据库提供的load指令进行插入。操作如下:
首先将准备好的数据导入到root目录下,新建一个itheima的数据库
客户端连接服务端时,加上参数 -–local-infile
mysql –-local-infile -u root -
设置全局参数local_infile为1,开启从本地加载文件导入数据的开关
set global local_infile = 1;
可以查看到local_infile已经为1
创建一个表
CREATE TABLE `tb_user` ( `id` INT(11) NOT NULL AUTO_INCREMENT, `username` VARCHAR(50) NOT NULL, `password` VARCHAR(50) NOT NULL, `name` VARCHAR(20) NOT NULL, `birthday` DATE DEFAULT NULL, `sex` CHAR(1) DEFAULT NULL, PRIMARY KEY (`id`), UNIQUE KEY `unique_user_username` (`username`) ) ENGINE=INNODB DEFAULT CHARSET=utf8 ;
执行load指令将准备好的数据,加载到表结构中
load data local infile '/root/sql1.log' into table tb_user fields terminated by ',' lines terminated by '\n' ;
可以看到插入的时间
在load时,主键顺序插入性能高于乱序插入
总结
批量插入数据
Insert into tb_test values(1,'Tom'),(2,'Cat'),(3,'Jerry');
手动控制事务
start transaction; insert into tb_test values(1,'Tom'),(2,'Cat'),(3,'Jerry'); insert into tb_test values(4,'Tom'),(5,'Cat'),(6,'Jerry'); insert into tb_test values(7,'Tom'),(8,'Cat'),(9,'Jerry'); commit;
主键顺序插入,性能要高于乱序插入
主键乱序插入 : 8 1 9 21 88 2 4 15 89 5 7 3 主键顺序插入 : 1 2 3 4 5 7 8 9 15 21 88 89
大规模数据时,可以使用load
主键优化
数据组织方式
在InnoDB存储引擎中,表数据都是根据主键顺序组织存放的,这种存储方式的表称为索引组织表 (index organized table IOT)。
行数据,都是存储在聚集索引的叶子节点上的
在InnoDB引擎中,数据行是记录在逻辑结构 page 页中的,而每一个页的大小是固定的,默认16K。 那也就意味着, 一个页中所存储的行也是有限的,如果插入的数据行row的大小大于该页的最大存储量,那么将会存储到下一个页中,页与页之间会通过指针连接。
页分裂
页可以为空,也可以填充一半,也可以填充100%。每个页包含了2-N行数据(如果一行数据过大,会行溢出),根据主键排列。
A. 主键顺序插入效果
①. 从磁盘中申请页, 主键顺序插
②. 第一个页没有满,继续往第一页插入
③. 当第一个也写满之后,再写入第二个页,页与页之间会通过指针连接
④. 当第二页写满了,再往第三页写入
B. 主键乱序插入效果
①. 加入1#,2#页都已经写满了,存放了如图所示的数据
②. 此时再插入id为50的记录,我们来看看会发生什么现象
不会再次开启一个页,插入到新页当中,**因为,索引结构的叶子节点是有顺序的。按照顺序,应该存储在47之后。**但是47所在的1#页,已经写满了,存储不了50对应的数据了。 那么此时会开辟一个新的页 3#。但是并不会直接将50存入3#页,而是会将1#页后一半的数据,移动到3#页,然后在3#页,插入50。
移动数据,并插入id为50的数据之后,那么此时,这三个页之间的数据顺序是有问题的。 1#的下一个页,应该是3#, 3#的下一个页是2#。 所以,此时,需要重新设置链表指针。
上述的这种现象,称之为 “页分裂”,是比较耗费性能的操作。
页合并
当我们对已有数据进行删除时,具体的效果如下: 当删除一行记录时,实际上记录并没有被物理删除,只是记录被标记(flaged)为删除并且它的空间变得允许被其他记录声明使用。
当我们继续删除2#的数据记录,当页中删除的记录达到 MERGE_THRESHOLD(默认为页的50%),InnoDB会开始寻找最靠近的页(前 或后)看看是否可以将两个页合并以优化空间使用。
删除数据,并将页合并之后,再次插入新的数据21,则直接插入3#页
这个里面所发生的合并页的这个现象,就称之为 “页合并”。
知识小贴士: MERGE_THRESHOLD:合并页的阈值,可以自己设置,在创建表或者创建索引时指定。
索引设计原则
- 满足业务需求的情况下,尽量降低主键的长度。
- 插入数据时,尽量选择顺序插入,选择使用AUTO_INCREMENT自增主键。
- 尽量不要使用UUID做主键或者是其他自然主键,如身份证号。
- 业务操作时,避免对主键的修改。
order by优化
MySQL的排序,有两种方式:
- Using filesort : 通过表的索引或全表扫描,读取满足条件的数据行,然后在排序缓冲区sort buffer中完成排序操作,所有不是通过索引直接返回排序结果的排序都叫 FileSort 排序。
- Using index : 通过有序索引顺序扫描直接返回有序数据,这种情况即为 using index,不需要额外排序,操作效率高。
对于以上的两种排序方式,Using index的性能高,而Using filesort的性能低,我们在优化排序操作时,尽量要优化为 Using index。
测试
把之前测试时,为tb_user表所建立的部分索引直接删除掉
drop index idx_user_phone on tb_user; drop index idx_user_phone_name on tb_user; drop index idx_user_name on tb_user;
执行排序SQL
explain select id,age,phone from tb_user order by age ;
由于 age, phone 都没有索引,所以此时再排序时,出现Using filesort, 排序性能较低。建立索引
create index idx_user_age_phone_aa on tb_user(age,phone);
创建索引后,根据age, phone进行升序排序
explain select id,age,phone from tb_user order by age
explain select id,age,phone from tb_user order by age , phone;
建立索引之后,再次进行排序查询,就由原来的Using filesort, 变为了 Using index,性能就是比较高的了。
创建索引后,根据age, phone进行降序排序
根据phone,age进行升序排序,phone在前,age在后。
排序时,也需要满足最左前缀法则,否则也会出现 filesort。因为在创建索引的时候, age是第一个 字段,phone是第二个字段,所以 排序时,也就该按照这个顺序来,否则就会出现 Using filesort。根据age, phone进行降序一个升序,一个降序
explain select id,age,phone from tb_user order by age asc , phone desc ;
因为创建索引时,如果未指定顺序,默认都是按照升序排序的,而查询时,一个升序,一个降序,此时 就会出现Using filesort。
为了解决上述的问题,我们可以创建一个索引,这个联合索引中 age 升序排序,phone 倒序排序。create index idx_user_age_phone_ad on tb_user(age asc ,phone desc);
然后再次执行如下SQL
explain select id,age,phone from tb_user order by age asc , phone desc ;
支持mysql8.0版本
order by 优化规则
- 根据排序字段建立合适的索引,多字段排序时,也遵循最左前缀法则。
- 尽量使用覆盖索引。
- 多字段排序, 一个升序一个降序,此时需要注意联合索引在创建时的规则(ASC/DESC)。
- 如果不可避免的出现filesort,大数据量排序时,可以适当增大排序缓冲区大小 sort_buffer_size(默认256k)。
group by优化
在没有索引的情况下执行group by
删除所有的索引
drop index idx_user_pro_age_sta on tb_user;
drop index idx_email_5 on tb_user;
drop index idx_user_age_phone_aa on tb_user;
drop index idx_user_age_phone_ad on tb_user;
执行查询语句
explain select profession , count(*) from tb_user group by profession ;
然后,我们在针对于 profession , age, status 创建一个联合索引。
create index idx_user_pro_age_sta on tb_user(profession , age , status):
然后执行:
explain select profession , count(*) from tb_user group by profession
只用age进行分组
explain select age, count(*) from tb_user group by age;
我们发现,如果仅仅根据age分组,就会出现 Using temporary ;而如果是 根据 profession,age两个字段同时分组,则不会出现 Using temporary。原因是因为对于分组操作, 在联合索引中,也是符合最左前缀法则的。
分组优化规则
所以,在分组操作中,我们需要通过以下两点进行优化,以提升性能:
- 在分组操作时,可以通过索引来提高效率。
- 分组操作时,索引的使用也是满足最左前缀法则的。
limit优化
在数据量比较大时,如果进行limit分页查询,在查询时,越往后,分页查询效率越低。
limit分页查询耗时对比
通过测试我们会看到,越往后,分页查询效率越低,这就是分页查询的问题所在。
优化思路: 一般分页查询时,通过创建覆盖索引能够比较好地提高性能,可以通过覆盖索引加子查 询形式进行优化。
不使用索引进行搜索
select * from tb_user limit 999000,10;
使用索引进行搜索
mysql> select id from tb_user order by id limit 999000,10;
使用覆盖查询+套接子查询进行搜索
explain select * from tb_user t , (select id from tb_user order by id limit 999000,10) a where t.id = a.id;
count优化
select count(*) from tb_user
如果说要大幅度提升InnoDB表的count效率,主要的优化思路:自己计数(可以借助于redis这样的数 据库进行,但是如果是带条件的count又比较麻烦了)。
count用法
count() 是一个聚合函数,对于返回的结果集,一行行地判断,如果 count 函数的参数不是 NULL,累计值就加 1,否则不加,最后返回累计值。
用法:count(*)、count(主键)、count(字段)、count(数字)
按照效率排序的话,count(字段) < count(主键 id) < count(1) ≈ count(),所以尽 量使用 count()。
update优化
update course set name = 'javaEE' where id = 1 ;
当我们在执行删除的SQL语句时,会锁定id为1这一行的数据,然后事务提交之后,行锁释放。
但是当我们在执行如下SQL时。
update course set name = 'SpringBoot' where name = 'PHP' ;
当我们开启多个事务,在执行上述的SQL时,我们发现行锁升级为了表锁。 导致该update语句的性能 大大降低。因为name字段并没有索引。
InnoDB的行锁是针对索引加的锁,不是针对记录加的锁 ,并且该索引不能失效,否则会从行锁升级为表锁 。
nt(主键 id) < count(1) ≈ count(),所以尽 量使用 count()。
update优化
update course set name = 'javaEE' where id = 1 ;
当我们在执行删除的SQL语句时,会锁定id为1这一行的数据,然后事务提交之后,行锁释放。
但是当我们在执行如下SQL时。
update course set name = 'SpringBoot' where name = 'PHP' ;
当我们开启多个事务,在执行上述的SQL时,我们发现行锁升级为了表锁。 导致该update语句的性能 大大降低。因为name字段并没有索引。
InnoDB的行锁是针对索引加的锁,不是针对记录加的锁 ,并且该索引不能失效,否则会从行锁升级为表锁 。
所以进行update的时候,尽量使用索引进行判断。
边栏推荐
- Navicat防止新建查询误删
- DataX tutorial (09) - how does dataX achieve speed limit?
- Uncaught typeerror cannot set properties of undefined (setting 'classname') reported by binding onclick event in jsfor loop
- Understand what MTU is
- In a single-page app, what is the right way to deal with wrong URLs (404 errors)?
- What is the slice flag bit
- R & D thinking 07 - embedded intelligent product safety certification required
- 【ROS2】为什么要使用ROS2?《ROS2系统特性介绍》
- [轻松学会shell编程]-5、计划任务
- After unplugging the network cable, does the original TCP connection still exist?
猜你喜欢
Derivation of COS (a-b) =cosa*cosb+sina*sinb
Power representation in go language
joda.time获取日期总结
Ht7180 3.7V L 12v/2a built in MOS high current boost IC solution
After unplugging the network cable, does the original TCP connection still exist?
How to realize hierarchical management of application and hardware in embedded projects
ACWING/2004. Misspelling
Wechat applet authorization login + mobile phone sending verification code +jwt verification interface (laravel8+php)
keil debug查看变量提示not in scope
Face++ realizes face detection by flow
随机推荐
2022 biological fermentation Exhibition (Jinan), which is a must read before the exhibition. The most comprehensive exhibition strategy will take you around the "fermentation circle"
TorchServe避坑指南
Understand what MTU is
Wechat applet simply realizes chat room function
Explain @builder usage
DataX tutorial (10) - hot plug principle of dataX plug-in
BigDecimal. Summary of setscale usage
JS to determine whether an element exists in the array (four methods)
cos(a-b)=cosa*cosb+sina*sinb的推导过程
Large funds support ecological construction, and Plato farm builds a real meta universe with Dao as its governance
Cs4344/ht5010 stereo d/a digital to analog converter
十大券商公司哪个佣金最低,最安全可靠?有知道的吗
The perfect presentation of Dao in the metauniverse, and platofarm creates a farm themed metauniverse
How to chain multiple different InputStreams into one InputStream
Bcrypt password encryption kalrry
[short time energy] short time energy of speech signal based on MATLAB [including Matlab source code 1719]
ASP. Net core - Safety of asynclocal in asp NET Core
What is cloud primordial?
北京网上开股票账户安全吗?
集群常用群起脚本