mysql优化经验

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);


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值