书写高质量的sql

1. 尽量避免在字段开头模糊查询,会导致数据库引擎放弃索引进行全表扫描

select * from user where name like ‘%晓%’

优化方式:尽量在字段后面使用模糊查询

select * from user where name like ‘晓%’

2. 查询条件不能用 <> 或者 !=

3. order by 条件要与where中条件一致,否则order by不会利用索引进行排序

不走索引

select * from user oder by age

走索引

select * from user where age > 0 order by age

4. 避免出现select *的出现

select*会将所有数据的列全部取出,应该根据业务的实际需求取出对应的列

select * from user where age > 5

正确写法:

select id name age from user where age > 5

5. 使用表的别名,当在SQL语句中连接多个表时,请使用表的别名并把别名前缀于每个列名上。这样就可以减少解析的时间并减少哪些列名歧义引起的语法错误

6. 避免在where条件中等号的左侧进行表达式,函数操作

select * from user age-2 = 10

正确写法:

select * from user age = 10 + 2

7. 尽量避免null值的判断

select * from user where name = null

正确写法: 将name的默认值设置为0

select * from user where name = 0

8. 尽量避免使用or

select * from user where age = 1 or age = 2

正确写法:

select * from user where age = 1

union all

select * from user where age = 2

9. 尽量避免使用in和not in

select * from user where id in (2,3)

正确写法:

select * from user where id between 2 and 3

10. 使用varchar代替char

因为varchar是变长类型,char是定长类型

11. 字符串应该带上引号

未走索引

select * from user where name = 张三

走索引

select * from user where name = ‘张三’

12. 不要超过5个表以上的连接

13. 尽量使用union all替代union

union会将最后结果的重复数据去掉,而union all则是将所有数据全部返回,不管是否有重复数据

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值