zoukankan      html  css  js  c++  java
  • sql 优化

    通过执行计划explain 分析时候用到了索引查询

    EXPLAIN select * from select_course where id = 1

     说明使用了主键索引

    字段要独立出现

    比如下面两条SQL语句在语义上相同,但是第一条会使用主键索引而第二条不会。

    select * from user where id = 20-1;
    select * from user where id+1 20;
     

    like查询,不能以通配符开头

    select * from article where title like '%mysql%';

    这种SQL的执行计划用不了索引(like语句匹配表达式以通配符开头),因此只能做全表扫描,效率极低,在实际工程中几乎不被采用。而一般会使用第三方提供的支持中文的全文索引来做。

    复合索引只对第一个字段有效

    建立复合索引:

     
    alter table person add index(first_name,last_name);

    其原理就是将索引先按照从first_name中提取的关键字排序,如果无法确定先后再按照从last_name提取的关键字排序,也就是说该索引表只是按照记录的first_name字段值有序。

    因此select * from person where first_name = ?是可以利用索引的,而select * from person where last_name = ?无法利用索引。

    那么该复合索引的应用场景是什么?==组合查询==

    比如对于select * person from first_name = ? and last_name = ?,复合索引就比对first_name和last_name单独建立索引要高效些。很好理解,复合索引首先二分查找与first_name = ?匹配的记录,再在这些记录中二分查找与last_name匹配的记录,只涉及到一张索引表。而分别单独建立索引则是在first_name索引表中二分找出与first_name = ?匹配的记录,再在last_name索引表中二分找出与last_name = ?的记录,两者取交集。


    or,两边条件都有索引可用

    一但有一边无索引可用就会导致整个SQL语句的全表扫描

     
    然后优化
     
     
    但是数据量达到千万级别 ,上亿级别数据,就得使用分库分表来加快查询
    Mycat 分库分表
    sharding-jdbc
    或 es 搜索引擎等
     
  • 相关阅读:
    Find the Smallest K Elements in an Array
    Count of Smaller Number
    Number of Inversion Couple
    Delete False Elements
    Sort Array
    Tree Diameter
    Segment Tree Implementation
    Java Programming Mock Tests
    zz Morris Traversal方法遍历二叉树(非递归,不用栈,O(1)空间)
    Algorithm about SubArrays & SubStrings
  • 原文地址:https://www.cnblogs.com/wanjun-top/p/12686690.html
Copyright © 2011-2022 走看看