SQL优化(一)

索引和拆分表可以极大的增加查询速度

我们的在写sql的时候也可以通过优化来增加查询速度.

  1. 对查询进行优化,要尽量避免全表扫描,首先应考虑在whereorder by 涉及的列上建立索引.

  2. 应尽量避免在where子句中对字段进行null值判断,否则将导致引擎放弃使用索引而进行全表扫描.如:
    select * from table where colum is null
    最好不要给数据库留null,尽可能使用NOT NULL填充数据
    备注,描述,评论之类的可以设置为NULL,其他的最好不要使用NULL
    尽量使用varchar,因为NULL在char类型就会占所设置的字符数.在varchar中NULL不会占用空间
    可以 对于数字类型的直接设置为0

  3. 应尽量避免where子句中使用 !=<> 操作符,否则将引擎放弃使用索引而进行全表 扫描

  4. 应尽量避免在where子句中使用 or 来连接条件,如果一个字段有索引,一个字段无索引,会导致引擎放弃使用索引,
    如: select * from table where age=10 or name=‘wlx’
    可以改成
    select * from table where age=10 union all
    select * from table where name=‘wlx’.

  5. innot in 也要慎用,否则会导致全表扫描,如
    select * from table where age in (1,2,3);
    对于连续的数值我们可以用 between 不用 in
    select * from table where age between 1 and 3
    很多时候用 exists 代替 in
    select * from table1 where age in (select age from table2); 可以用一下语句替换
    select * from table1 t1 where exists(select age from table2 where age=t1.age);

  6. 下面的查询也 将导致全表扫描
    select * from table where name like ‘%aaaa’;
    若要提高效率,可以考虑全文检索

  7. 如果where子句中使用参数,也会导致全表扫描.因为SQL只有在运行时才会解析局部变量,但优化程序不能将访问计划的选择推迟到运行时;它必须在编译时进行选择. 然而如果在编译时建立访问计划,变量的值还是未知的 ,因而无法作为索引选择的输入项.如果下面语句将进行全表扫描.
    select * from table where age=@age
    可以改为强制查询使用索引
    select * from table with(index(索引)) where age =@age
    应尽量避免在where 子句中对字段进行表达式操作,这将导致引擎放弃使用索引而进行全表扫描.如
    select * from table age/2=11 可以改为
    select * from table age=11*2

  8. 应尽量避免在where子句中对字段进行函数操作,这将导致引擎放弃使用索引而进行全表扫描.如
    select * from table substring(name,1,3) = ‘abc’; //查询name以abc开头的数据
    select * from table where datediff(createdate,‘2019-07-04’)=0 //查询createdate和2019-07-04相等的数据
    可以改为 select * from table where name=‘ABC%’
    select * from table where createdate>=2019-07-04 and createdate< 2019-07-04

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值