作者:LING2502856847 | 来源:互联网 | 2023-07-11 10:06
1.大批量插入数据时的优化mysql数据导入数据是通过load命令进行的,但是适当的设置能够提高导入的效率--local代表从本地中的文件系统中进行数据导入--
1. 大批量插入数据时的优化
mysql 数据导入数据是通过load 命令进行的,但是适当的设置能够提高导入的效率
-- local 代表从本地中的文件系统中进行数据导入
-- 以csv 文件为例
load data local infile 'filename' into table tb_name fields terminated by ',' lines terminated by '\n';
1)主键顺序插入:数据按主键的顺序在文件中从第一行开始往下放
2) 关闭唯一性校验
set unique_checks=0;
-- 导入完成之后
set unique_checks=0;
3)手动提交事务(关闭自动提交)
2. 优化inset 语句
1)对同一张表插入多条数据,应该使用inset 语句块,而不是分开执行
insert into tb_test values(1, 'Tom');
insert into tb_test values(2, 'Cat');
insert into tb_test values(3, 'Jerry');
==>
insert into tb_test values (1, 'Tom'),(2, 'Cat'),(1, 'Jerry');
2)在事务中进行数据插入
3)数据有序插入
3. 优化嵌套子查询
尽量用多表联查来替换嵌套子查询
4. 优化group by
使用order by null 来取消隐式的排序。但是在MySQL 8.0.x 中已经取消了隐式的 order by。
5. 优化or 条件
确保or 条件中的字段均存在索引。
6. 分页查询优化
1. 优化思路一
在索引上完成排序分页操作,最后根据主键关联回原表查询所需要的其他列内容
select id from item order by id limit 2000000, 10;select * from tb_item t, (select id from item order by id limit 2000000, 10) a where a.id = t.id;
2. 优化思路二(不太好,因为id自增但不一定连续)
该方案适用于主键自增的表,可以把limit 查询转换成某个位置的查询。
select * from tb_item where id > 2000000, 10;
7. 使用SQL 提示
1. use index
建议MySQL 数据库使用某个索引,不一定采用
select * from tb_seller use index(idx_name) where name = "小米科技";
2. ignore index
建议MySQL 数据库不使用某个索引,不一定采用
3. force index
强制使用某个索引