SQL书写建议

1.查询SQL尽量不要使用 select*,而是select具体字段
2.知道查询结果只有一条或者只要最大/最小一条记录,建议使用limit 1
    加上limit 1之后,只要找到了对应的一条记录,就不会继续向下扫描了,以提高效率
    如果有唯一索引在语句中的话,因为limit的存在主要就是为了防止全表扫描,从而提高性能,
    如果一个语句本身可以预知不用全表扫描,有没有limit性能差别不大,可加可不加
3.应尽量避免在where子句中使用or来连接条件
    select * from user where id = 1 or age = 5
    建议使用 union all
    select * from user where id = 1 union all select * from user where age = 5
    或者分成两条sql
    select * from user where id = 1
    select * from user where age = 5
4.优化limit分页
    当偏移量特别大的时候,查询效率就变得低下
    反例:select id,nam,age from user limit 10000,10
    正例:select id,name,age fromuser where id>10000 limit 10
5.优化 like语句
    反例:select id,name,age from user where name like '%老虎';
6.使用where条件限定要查询的数据,避免返回多余的行
    反例:List<Long> ids = sqlMap.queryList("select id from user where isVip = 1");
        Boolean isVip = ids.contaions(id);
    正例:select id from user where id = 'id' and isVip=1;
7.尽量避免在索引列上使用mysql的内置函数
    假设login_time加了索引
    反例:select user_id,login_time from login_user where Date_ADD(login_time, Interval 7 DAY) >= now();
    正例:select user_id,login_time from login_user where login_time >= Date_ADD(now(), Interval - 7 DAY);
8.应尽量避免在where子句中对字段进行表达式操作
    反例:select * from user where age-1=10;  这样会导致系统放弃索引而进行全表扫描
    正例:select * from user where age = 11;
9.inner join,left join,right join,优先使用inner join,如果是left join,左边表结果尽量小
    inner join:内连接,在两张表进行连接查询时,只保留两张表中完全匹配的结果集
    left join:在两张表进行连接查询时,会返回左表所有的行,即使在右表中没有匹配的记录
    right join:在两张表进行连接查询时,会返回右表所有的行,即使在左表中没有匹配的记录
    最左匹配原则
10.应考虑在where及order by等涉及的列上建立索引
    select * from user where address='深圳' orde by age;
    alter table user add index_idx_address_age(address,age);
11.如果插入数据过多,考虑批量插入
    insert into user(name,age) values
    <foreach collection="list" item="item" index="index" separator=",">
    (#{item.name},#{item.age})
    </foreach>
12.小心使用distinct
    反例:select distinct * from user;
    正例:select distinct name from user;
13.删除冗余和重复索引
    反例:KEY `idx_userId` (`userId`)
        KEY `idx_userId_age` (`userId`,`age`)
    正例:KEY `idx_userId_age` (`userId`,`age`)
14.如果数据量较大,优化修改/删除语句
    反例:delete from user where id<10000;
    正例:用循环,每个循环删除几百个
15.where子句中考虑使用默认值代替null
    null有时候会导致索引失效
16.不要有三张以上表连接
17.exit和in的合理使用
18.尽量用union all替换union
    如果检索结果中不会有重复的记录,推荐使用union all替换 union
19.索引不应该太多,一般5个以内
    索引增加查询效率,降低增删改效率
20.尽量使用数字型字段,若只含数值信息的字段就不要设计为字符型
21.索引不适合建在有大量重复数据的字段上,如性别
    SQL优化器会根据数据量来进行查询优化,如果索引列有大量重负数据,会不走索引
22.尽量避免向客户端返回过多数据
23.尽可能使用varchar代替char
24.为了提高group by语句的效率,可以在执行到该语句前,把不需要的记录过滤掉
25.如果字段类型是字符串,where时一定用引号括起来,否则索引失效
    select * from user where user_id(varchar型)=123
    字段类型不匹配,会做隐式类型转换
26.写sql的时候,尽量养成一个explain的习惯,分析sql,尤其是分析索引这块。
 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值