MySQL 优化SQL语句

优化INSERT

insert into books values (1,'book1'),(2,'book2'),(3,'book3');

多条insert语句合并,一次性插入数据库


优化ORDER BY

select id,enmae,depno,sal from emp where depno=10;

对depno添加索引

1.对于order by [sort] limit [offset],[limit]的组合,只需在sort上建立索引

2.对于where [col]=[val] order by [sort]的组合,对col,sort建立索引

3.不要在where和order by使用表达式或函数,如:order by year(date)


优化GROUP BY

explain select id,count(data) from test group by id;

explain select id,count(data) from test group by id order by null;

//由于group by会对结果自动排序
//第一个SQL使用了using filesort
//第二个SQL没有,减少了文件排序的步骤


优化OR

select * from tb_1 where type='1' or status='2';

当查询条件中只有or关键字,且字段列都有索引时,才能使用索引,这里tb_1表上type和status字段上都要有索引。

or相当于分别使用各个条件查询后使用union合并结果集


优化嵌套查询

使用连接(join)查询替代子查询,因为连接查询不需要创建临时表


优化插入记录的速度

MyISAM引擎

1、禁用索引

alter table table_name disable keys;

-- insert SQL

alter table table_name enable keys;

2、禁用唯一性检查

set unique_checks = 0;

-- insert SQL

set unique_checks = 1;

3、使用LOAD命令批量插入

load data infile 'data.txt' into table table_name;

InnoDB引擎

1、禁用唯一性检查

2、禁用外检检查

set foreign_key_checks = 0;

-- insert SQL

set foreign_key_checks = 1;

3、禁止自动提交

set autocommit = 0;

-- insert SQL

set autocommit = 1;

猜你喜欢

转载自blog.csdn.net/qq_17613195/article/details/84224411