影响sql性能的写法

1、避免在where子句中使用 is null 或 is not null 对字段进行判断。

    如:select id from table where name is null

2、避免在 where 子句中使用 != 或 <> 操作符。

    如:select name from table where id <> 0

数据库在查询时,对 != 或 <> 操作符不会使用索引,而对于 < 、 <= 、 = 、 > 、 >= 、 BETWEEN AND,数据库才会使用索引。
因此对于上面的查询,正确写法应该是:

    select name from table where id < 0

    union all

    select name from table where id > 0

3、避免在 where 子句中使用 or来链接条件。

    如:select id from tabel where name = 'UncleToo' or name = 'PHP'

这种情况,我们可以这样写:

    select id from tabel where name = 'UncleToo'

    union all

    select id from tabel where name = 'PHP'

4、少用 in 或 not in。

虽然对于 in 的条件会使用索引,不会全表扫描,但是在某些特定的情况,使用其他方法也许效果更好。如:

select name from tabel where id in(1,2,3,4,5)

像这种连续的数值,我们可以使用 BETWEEN AND,如:

    select name from tabel where id between 1 and 5

5、注意 like 中通配符的使用。

下面的语句会导致全表扫描,尽量少用。如:

    select id from tabel where name like'%UncleToo%'

    或者

    select id from tabel where name like'%UncleToo'

而下面的语句执行效率要快的多,因为它使用了索引:

    select id from tabel where name like'UncleToo%'

6、避免在 where 子句中对字段进行表达式操作。

    如:select name from table where id/2 = 100

正确的写法应该是:

    select name from table where id = 100*2

7、避免在 where 子句中对字段进行函数操作。

    如:select id from table where substring(name,1,8) = 'UncleToo'

    或

    select id from table where datediff(day,datefield,'2014-07-17') >= 0

这两条语句中都对字段进行了函数处理,这样就是的查询分析器放弃了索引的使用。正确的写法是这样的:

    select id from table where name like'UncleToo%'

    或

    select id from table where datefield <= '2014-07-17'

★也就是说,不要在 where 子句中的 = 左边进行函数、算术运算或其他表达式运算。


8、在子查询中,用 exists 代替 in 是一个好的选择。

    如:select name from a where id in(select id from b) 

如果我们将这条语句换成下面的写法:

    select name from a where exists(select 1 from b where id = a.id)

这样,查询出来的结果一样,但是下面这条语句查询的速度要快的多。

  • 0
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

西贝爷

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值