一,SQL优化
主要解决海量数据操作时的全表搜索,所以减少不必要的全表搜索是SQL优化的主要目的,下面总结一下常用的优化有哪些:
1,避免在where条件中使用!=或者<>,这样会是的查询放弃索引而进行全局扫描
2,避免在where条件中使用is null使用 默认值替换null,如默认值为0
select id from table_name where column is null;
select id from table_name where column = 0;
3,尽量在where条件,order by中建立索引进行操作
4,尽量用exits代替in使用
select name from a where id in (select id from b);
select name form a where exists (select 1 from b where a.id = b.id); 5,避免使用or关键字 用union all 代替
select name from a where id = 1 or id =2;
select name from a where id = 1
union all
select name form a where id = 2;
6,尽量不使用like "%***%" 会全表搜索,可以用and like "***%"代替
7,count(*), count(column), count(primary key), count(1) 其中前两者是一样的后两个效率较高
8,避免在where条件中对字段进行表达式操作,同样尽量少对字段不要使用函数操作
select id from a where num/2 = 10;
select id from a where num = 10*2; 9,
在使用索引字段作为条件时,如果该索引是组合索引,那么必须使用到该索引中的第一个字段作为条件时才能保证系统使用该索引,否则该索引将不会被使 用,并且应尽可能的让字段顺序与索引顺序相一致。
create index a_index on a (id, name);
select id from a where id > 10 and order by name;
二,索引
索引是一张表的一个目录,SQL查询数据时先使用索引进行定位,这样很大的提高查询效率,索引一般使用在where条件中,索引分为五种
1,主键索引
每个表默认有一个主键索引作用在表的主键上面,
a. 创建索引
create table table_name (
id int auto_increment primary key, -- 有一个默认索引作用在主键上
name varchar(20)
)
或者
create table table_name (
id int auto_increment,
name varchar(20)
);
alter table_name add primary key(id); --设置主键 默认创建一个主键索引

本文详细介绍了MySQL的SQL优化技巧,如避免全表搜索、合理使用索引,并探讨了索引类型如主键、唯一和组合索引。此外,还讲解了视图的概念及其在数据封装上的应用,触发器的使用来确保数据完整性,以及存储过程的优势,如增强SQL灵活性和提升安全性。
最低0.47元/天 解锁文章
521

被折叠的 条评论
为什么被折叠?



