您的位置:首页 > 数据库 > MySQL

mysql优化经验

2018-02-13 21:06 197 查看
1.避免 select *  用具体的字段代替*,不要返回无用的字段
2.应该尽量避免在where字句中使用!=或<>操作符
3.应该尽量避免在where字句中对字段进行null判断
    select id from 表名 where num is null; (判断是否为null不能使用=)

可以在num上设置默认值,比如0,确保表中没有null值,然后这样查询:
select id from 表名 where num=0;
4.应该尽量避免在where字句中使用or来连接条件
select id from 表名 num=10 or num=20;
可以这样查询
select id from 表名 where num=10;
union all
select id from 表名 where num=20;
5.使用like模糊查询会导致全表扫描
如 select id from t where num like '%123%'
若要提高效率可以使用全文检索技术
6.尽量避免in 和 not in
select id from t  name in(1,2,3,4);
对于连续的数值可以用between 
select id from t between  1 and 4;
使用exists代替in,是一个好的选择
select num from a where num in(select num from b);
用下面的语句替换
select num from a where exists(select )
 not in 优化
select ID,name from Table_A where ID not in (select ID from Table_B)

这句是最经典的not in查询了。改为表连接代码如下:

select Table_A.ID,Table_A.name from Table_A left join Table_B on Table_A.ID=Table_B.ID and Table_B.ID is null
或者:
select Table_A.ID,Table_A.name from Table_A left join Table_B on Table_A.ID=Table_B.ID where Table_B.ID is null

7.应该尽量避免在where字句中对字段进行表达式操作,如
select id from t where num/2=100;
应该为:
select id from where num=100*2;
8.不要在where字句中的“=”左边进行函数、算数运算或其他表达式运算,否则系统将可能无法正确使用索引
9.尽量使用数字型字段
    一部分开发人员和数据库管理人员喜欢把包含数值信息的字段,设计为字符型,这会降低查询和连接的性能,并会增加存储开销,这是因为引擎在处理查询和连接会逐个比较字符串中每一个字符,而对于数字型而言只需要比较一次就够了

10.能够用distinct就不要用group by
11.程序中如果一次性对同一个表插入多条数据,把他拼成一条效率会更高,如下句
insert into person(name,age) values(‘xboy’, 14); 
insert into person(name,age) values(‘xgirl’, 15); 
insert into person(name,age) values(‘nia’, 19); 
把它拼成一条语句执行效率会更高.
 insert into person(name,age) values(‘xboy’, 14), (‘xgirl’, 15),(‘nia’, 19);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: