• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
Foreordination
酒后高歌磨剑,梦中快意恩仇,名利脚下踩,情义两肩挑
博客园    首页    新随笔    联系   管理    订阅  订阅
二、工作中常用的SQL优化

除了给table建立索引之外,保持良好的SQL语句编写。

1、通过变量的方式来设置参数

  比如动态查询的时候,尽量这样写

好:string strSql=" SELECT * FROM PEOPLE P WHERE P.ID=? ";
坏:string strSql=" SELECT * FROMM PEOPLE P WHERE P.ID= "+ID;

数据库的SQL解析和执行会保存在缓存中,SQL只要有变化,就要重新解析。而"where p.id="+id的方式在id值发生改变得时候需要重新解析SQL,浪费时间。

2、尽量不要使用select *

好:string strSql=" select id,name from people ";
坏:string strSql=" slect I from people";

select * 会增加SQL解析的时间,而且把不需要的数据也查询了出来,数据传输很浪费时间。

3、谨慎使用模糊查询

好:string strSql=" select * from people p where p.id like 'parm%' ";
坏:string strSql=" select * from people p where p.id like '%parm%' ";

当模糊匹配以%开头,这一列的索引将彻底失效,导致全表扫描,如果不以%开头,则这一列的索引还是有效的。

4、优先使用UNION ALL,避免使用UNION

好:string strSql=" select name from people union all select name from teacher ";
坏:string strSql=" select name from people union select name from teacher ";

因为UNION会将各查询的子集记录进行比较,比起来UNION ALL,速度会慢很多。

5、在where语句或者order by语句中,避免对索引字段进行计算操作。

好:string strSql=" select name ,age from people where date=? ";
坏:string strSql=" select name,age from people wehre trunc(date)=? ";

6、永远为每张表设置一个ID

数据库的每一张表都应该设置一个ID作为主键,而且是int型,推荐使用UNSIGNED,并且设置上自动增加的AUTO_INCREMENT的标志。

即使你的people表有一个主键叫做name的字段,你也别让它成为主键,使用varchar类型作为主键会使得性能下降。

 

posted on 2018-03-15 14:21  Foreordination  阅读(212)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3