Mysql 查询优化

where 子句中不要使用 !=<> 
where , order by 操作会涉及到的列上建立索引
where 子句中不要对字段进行 null 值判断

将可能出现空值的列设置为 0
在查询时,可以通过

select 字段 from 表名 where 另一个字段=0
where 子句中,不要在条件上添加 or
select id from t where num=10 or num=20

优化写法
select id from t where num=10
union all
select id from t where num=20
where 子句中,使用 like 也会导致进行全表扫描
where 子句中 innot in ,可以不用尽量不用

对于连续的数值,可以使用 between 进行选择

select id from t where num in(1,2,3)

优化

select id from t where num between 1 and 3
where 子句中,如果一定要有参数,可以修改为强制查询使用索引

select id from t where num=
优化
select id from t with(index(索引名)) where num=
Mysql

SELECT * FROM t force index(指定的索引名称) WHERE num = 值;

where 子句中,不要使用表达式操作

select id from t where num/2=100

优化

select id from t where num=100*2

where 子句的查询条件不要写为 函数
where 子句的左侧不要进行函数 算术运算 其他表达式运算,可能影响系统无法使用索引
使用 exists 代替 in 


select num from a where num in(select num from b)


优化

select num from a where exists(select 1 from b where num=a.num)

建立索引可以提高 select 的效率,但是会降低 insertupdate 的效率

原因为 insertupdate 有时会重新创建索引
可以使用数值型类型的字段,使用数值型字段
使用字符串类型的字段,会导致多次判断,降低速度
尽量不要使用 select * from 表名
使用 select 字段 from 表名 

https://www.jb51.net/article/209199.htm

 

posted @ 2021-10-06 16:02  CodeYaSuo  阅读(36)  评论(0编辑  收藏  举报