Sql优化二三事

1.Where条件
        将过滤数据量大的条件放在前面,先行过滤
    
2.不要使用select * 
       只把需要使用的字段返回
    
3.使用临时表暂时存储数据
    
4.使用Exists替换in
        in不会使用索引: select * from A a where a.id in (select id from B)
        Exists替换in写法: select * from A a where exists (select * from B b where a.id = b.id)

5.对于连续的数据使用between 抛弃使用in
        select * from A where id in (1,2,3,4,5)
        优化:
        select * from A where id between(1,5)
    
6.避免使用or,使用union替换or,or会导致全表扫描
        select * from A where id =1 or id =3
        优化: select * from A where id =1 union select * from A where id =3
    
7.避免进行null值的判断,会导致数据库引擎放弃索引进行全表扫描
        select * from A where score is null
        优化:select * from A where score = 0
    
8.使用Where替换Having
        Having是检索出所有数据后才会过滤数据,Where是先过滤后才会检索出数据
    
9.避免在字段开头使用模糊查询,会导致数据库引擎放弃索引进行全表扫描
        select * from A where username like '%Wei%'
        优化方案: select * from A where username like 'Wei%'
    
10.尽量避免在Where 条件中等号的左侧进行表达式,函数操作,会导致数据库引擎放弃索引进行全表扫描
        -- 全表扫描
            select * from A where score/10 = 9
        -- 走索引    
            select * from A where score = 9*10
    
11.查询中避免对索引列使用函数
        -- 全表扫描
            select * from A where concat('P',id) = 'P1318899'
        -- 走索引    
            select * from A where id = SUBSTRING('P1318899',2,8)
    
12.使用表的别名
        多表连接查询时,使用表的别名在每个列名前,减少解析时间
        
13.避免使用!=和<>
        会放弃索引的使用

14.外连接查询过程中会对左右表进行扫描,降低查询效率,因此尽量使用内连接

  

    SELECT语句 - 执行顺序:
        FROM
            <表名> # 选取表,将多个表数据通过笛卡尔积变成一个表。
        ON
            <筛选条件> # 对笛卡尔积的虚表进行筛选
        JOIN <join, left join, right join...>
            <join表> # 指定join,用于添加数据到on之后的虚表中,例如left join会将左表的剩余数据添加到虚表中
        WHERE
            <where条件> # 对上述虚表进行筛选
        GROUP BY
            <分组条件> # 分组
            <SUM()等聚合函数> # 用于having子句进行判断,在书写上这类聚合函数是写在having判断里面的
        HAVING
            <分组筛选> # 对分组后的结果进行聚合筛选
        SELECT
            <返回数据列表> # 返回的单列必须在group by子句中,聚合函数除外
        DISTINCT
            # 数据除重
        ORDER BY
            <排序条件> # 排序
        LIMIT
            <行数限制>

     
    

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值