数据库涉及大量数据查询时的注意事项

本文介绍了如何避免频繁数据库操作、优化表设计、合理使用索引,包括避免!=和<>操作、null值判断、or条件、like和in查询等,以降低IO消耗并确保查询效率。通过实例和解决方案,帮助开发者提高数据库性能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  1. 避免频繁连接和关闭数据库,这样会导致IO访问次数太频繁。

  2. 设计表时要建立适当的索引,尤其要在 where 及 order by 涉及的列上建立索引

  3. 避免全表扫描,以下情况会导致放弃索引直接进行全部扫描

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

  • 避免在 where 子句中对字段进行 null 值判断

    select id from table where num is null

    解决方法:建表时设置默认值0,也就是将null用0填充,然后查询:
    select id from table where num=0

  • 避免在 where 子句中使用 or 来连接条件,否则将导致引擎放弃使用索引而进行全表扫描

    select id from t where num=10 or num=20

    解决方法:使用 union

    select id from t where num=10 union all select id from t where num=20

  • 避免使用 like

    select id from t where name like ‘%abc%’

    解决方法:使用全文检索

  • 避免使用 in 和 not in

    select id from t where num in(1,2,3)

    解决方法1:连续值使用 between
    解决方法2:用 exists 替换 in
    select num from a where exists(select 1 from b where num=a.num)

  • 避免使用参数

    select id from t where num=@num

    解决方法:强制查询使用索引

    select id from t with(index(index_name)) where num=@num

  • 避免表达式操作

    select id from t where num/2=100

    解决方法:select id from t where num=100*2

  • 避免函数操作

    select id from t where substring(name,1,3)=’abc’ 查询以abc开头的id

    解决方法:全文索引

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

白墨石

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

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

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

打赏作者

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

抵扣说明:

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

余额充值