提高 MySQL查询效率的方法
- 选择有效的表名顺序select语句一般优先处理写在from子句最后的表,将记 录条数最少或者父表(被参考表)放在最后可提高查询效率。
- select 尽量避免使用 * ,* 如果不需要查询所有属性的话,尽量把需要查询的字段一一写出来,而不是用 * 代替。比如说一共有10个字段,你需要查询其中的9个字段,把9个字段都写上更好,在满足需求的情况下,能少查一个字段就少查一个字段。
- 整合简单的数据库查询语句,能一次性查询出来的属性就不要分为两次或者多次查询。
- 尽可能使用where替换having,能使用where解决的就不要使用分组查询的having子句,因为having是查询所有记录之后,再进行分组过滤,其中可能还需呀排序和统计等,比较繁琐。
- .尽量多用内部函数,少用运算符的自己进行的操作。
- 多使用表的别名,以减少解析时间。
- 尽量使用exists代替in,not exists代替not in。
- 尽量用>=代替>等。如:有时候>5和>=6所查询的效果是一样的,但是一个是先找5,一个是先找6.多找了一个数。
视图 view
创建表并插入数据
create table if not exists people_tb
(
age int,
sex enum('男','女'),
height int
);
insert into people_tb values
(15,'男',160),
(18,'男',170),
(19,'女',160),
(22,'男',180),
(20,'女',170);
创建视图
格式: create view 视图名 as 查询语句;
create view people_view as select * from people_tb;
使用视图(查询)
格式: 查询语句 视图名;
select age from people_view;
select * from people_view;
修改视图
格式: alter view 视图名 as 查询语句;
alter view people_view as select age,sex from people_tb;
删除视图
格式: drop view 视图名;
drop view people_view;
索引 index
- 创建普通索引
格式: create index 索引名 on 表名(列名(length));
允许定义索引的字段重复和空值
create index normal_indexon people_tb(age(4));
- 创建唯一索引
格式: create unique index 索引名 on 表名(列名(length))
允许定义索引的字段空值
- 创建全文索引
格式: create fulltext index 索引名 on 表名(字段名(length))
- 删除索引
格式: drop index 索引名 on 表名;
drop index normal_index on people_tb;
- 添加普通索引
格式: alter table 表名 add index 索引名(列名(长度));
alter table people_tb add index normal_index(height(4));
查询索引
show index from 表名;
查询索引键值
show keys from 表名;