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

  • 相关阅读:
    使用事务和SqlBulkCopy导入大批量数据
    Windows Server中禁止Administrator用户登录远程桌面
    SQL和C#的常用时间日期处理
    转:SQL Server数据库查询速度慢的原因
    火把节之夜,想发飙
    判断一个字符串是否为空
    .net中的using批注
    [转帖]删除鼠标右键的“用阿里旺旺打开此文件”的命令
    近凌晨12点却毫无睡意
    SQL SERVER取得汉字的拼音缩写
  • 原文地址:https://www.cnblogs.com/drq1/p/8573387.html
Copyright © 2020-2023  润新知