zoukankan      html  css  js  c++  java
  • 二、工作中常用的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类型作为主键会使得性能下降。

  • 相关阅读:
    Nginx 413 Request Entity Too Large
    tp U函数 logs
    div + css 边框 虚线
    html+css判断各个IE浏览器版本
    win7 cmd 常用命令
    mysql 常用命令
    ThinkPHP学习(二)理清ThinkPHP的目录结构及访问规则,创建第一个控制器
    将字符串 由一个字符集 转成 另一个字符集 及 随机生成中文
    Sublime Text 3 中实现编译C语言程序
    C语言入门
  • 原文地址:https://www.cnblogs.com/drq1/p/8573387.html
Copyright © 2011-2022 走看看