1. 程式人生 > 其它 >PAT 甲級 1018 Public Bike Management

PAT 甲級 1018 Public Bike Management

建索引的幾大原則

  1. 最左字首匹配原則

    mysql會一直向右匹配直到遇到範圍查詢(>、<、between、like)就停止匹配,比如a = 1 and b = 2 and c > 3 and d = 4 如果建立(a,b,c,d)順序的索引,d是用不到索引的,如果建立(a,b,d,c)的索引則都可以用到,a,b,d的順序可以任意調整。

  2. =和in可以亂序

    比如a = 1 and b = 2 and c = 3 建立(a,b,c)索引可以任意順序,mysql的查詢優化器會幫你優化成索引可以識別的形式。

  3. 儘量選擇區分度高的列作為索引

    區分度的公式是count(distinct col)/count(*),表示欄位不重複的比例,比例越大我們掃描的記錄數越少。唯一鍵的區分度是1,而一些狀態、性別欄位可能在大資料面前區分度就是0,那可能有人會問,這個比例有什麼經驗值嗎?使用場景不同,這個值也很難確定,一般需要join的欄位我們都要求是0.1以上,即平均1條掃描10條記錄。

  4. 索引列不能參與計算,保持列“乾淨”

    比如from_unixtime(create_time) = ’2014-05-29’就不能使用到索引,原因很簡單,b+樹中存的都是資料表中的欄位值,但進行檢索時,需要把所有元素都應用函式才能比較,顯然成本太大。所以語句應該寫成create_time = unix_timestamp(’2014-05-29’)。

  5. 儘量的擴充套件索引,不要新建索引

    比如表中已經有a的索引,現在要加(a,b)的索引,那麼只需要修改原來的索引即可。

select
   count(*) 
from
   task 
where
   status=2 
   and operator_id=20839 
   and operate_time>1371169729 
   and operate_time<1371174603 
   and type=2;

這個表的其他相關查詢:

select * from task where status = 0 and type = 12 limit 10;
select count(*) from task where status = 0 ;

根據最左匹配原則,最開始的sql語句的索引應該是status、operator_id、type、operate_time的聯合索引;其中status、operator_id、type的順序可以顛倒,可以覆蓋到所有情況。 利用了索引的最左匹配的原則

查詢優化神器 - explain命令

rows是核心指標,絕大部分rows小的語句執行一定很快(有例外,下面會講到)。所以優化語句基本上都是在優化rows。

慢查詢優化基本步驟

  1. 先執行看看是否真的很慢,注意設定SQL_NO_CACHE
  2. where條件單表查,鎖定最小返回記錄表。這句話的意思是把查詢語句的where都應用到表中返回的記錄數最小的表開始查起,單表每個欄位分別查詢,看哪個欄位的區分度最高
  3. explain檢視執行計劃,是否與1預期一致(從鎖定記錄較少的表開始查詢)
  4. order by limit 形式的sql語句讓排序的表優先查
  5. 瞭解業務方使用場景
  6. 加索引時參照建索引的幾大原則
  7. 觀察結果,不符合預期繼續從1分析

幾個慢查詢案例

不同的語句書寫方式對於效率往往有本質的差別

select
   distinct cert.emp_id 
from
   cm_log cl 
inner join
   (
      select
         emp.id as emp_id,
         emp_cert.id as cert_id 
      from
         employee emp 
      left join
         emp_certificate emp_cert 
            on emp.id = emp_cert.emp_id 
      where
         emp.is_deleted=0
   ) cert 
      on (
         cl.ref_table='Employee' 
         and cl.ref_oid= cert.emp_id
      ) 
      or (
         cl.ref_table='EmpCertificate' 
         and cl.ref_oid= cert.cert_id
      ) 
where
   cl.last_upd_date >='2013-11-07 15:03:00' 
   and cl.last_upd_date<='2013-11-08 16:00:00';
  1. 先執行一下,53條記錄 1.87秒,又沒有用聚合語句,比較慢

    53 rows in set (1.87 sec)
    
  2. explain

    +----+-------------+------------+-------+---------------------------------+-----------------------+---------+-------------------+-------+--------------------------------+
    | id | select_type | table      | type  | possible_keys                   | key                   | key_len | ref               | rows  | Extra                          |
    +----+-------------+------------+-------+---------------------------------+-----------------------+---------+-------------------+-------+--------------------------------+
    |  1 | PRIMARY     | cl         | range | cm_log_cls_id,idx_last_upd_date | idx_last_upd_date     | 8       | NULL              |   379 | Using where; Using temporary   |
    |  1 | PRIMARY     | <derived2> | ALL   | NULL                            | NULL                  | NULL    | NULL              | 63727 | Using where; Using join buffer |
    |  2 | DERIVED     | emp        | ALL   | NULL                            | NULL                  | NULL    | NULL              | 13317 | Using where                    |
    |  2 | DERIVED     | emp_cert   | ref   | emp_certificate_empid           | emp_certificate_empid | 4       | meituanorg.emp.id |     1 | Using index                    |
    +----+-------------+------------+-------+---------------------------------+-----------------------+---------+-------------------+-------+--------------------------------+
    

    簡述一下執行計劃,首先mysql根據idx_last_upd_date索引掃描cm_log表獲得379條記錄;然後查表掃描了63727條記錄,分為兩部分,derived表示構造表,也就是不存在的表,可以簡單理解成是一個語句形成的結果集,後面的數字表示語句的ID。derived2表示的是ID = 2的查詢構造了虛擬表,並且返回了63727條記錄。我們再來看看ID = 2的語句究竟做了寫什麼返回了這麼大量的資料,首先全表掃描employee表13317條記錄,然後根據索引emp_certificate_empid關聯emp_certificate表,rows = 1表示,每個關聯都只鎖定了一條記錄,效率比較高。獲得後,再和cm_log的379條記錄根據規則關聯。從執行過程上可以看出返回了太多的資料,返回的資料絕大部分cm_log都用不到,因為cm_log只鎖定了379條記錄。

    如何優化呢?可以看到我們在執行完後還是要和cm_log做join,那麼我們能不能之前和cm_log做join呢?仔細分析語句不難發現,其基本思想是如果cm_log的ref_table是EmpCertificate就關聯emp_certificate表,如果ref_table是Employee就關聯employee表,我們完全可以拆成兩部分,並用union連線起來,注意這裡用union,而不用union all是因為原語句有“distinct”來得到唯一的記錄,而union恰好具備了這種功能。如果原語句中沒有distinct不需要去重,我們就可以直接使用union all了,因為使用union需要去重的動作,會影響SQL效能。

    優化過的語句如下:

    select
       emp.id 
    from
       cm_log cl 
    inner join
       employee emp 
          on cl.ref_table = 'Employee' 
          and cl.ref_oid = emp.id  
    where
       cl.last_upd_date >='2013-11-07 15:03:00' 
       and cl.last_upd_date<='2013-11-08 16:00:00' 
       and emp.is_deleted = 0  
    union
    select
       emp.id 
    from
       cm_log cl 
    inner join
       emp_certificate ec 
          on cl.ref_table = 'EmpCertificate' 
          and cl.ref_oid = ec.id  
    inner join
       employee emp 
          on emp.id = ec.emp_id  
    where
       cl.last_upd_date >='2013-11-07 15:03:00' 
       and cl.last_upd_date<='2013-11-08 16:00:00' 
       and emp.is_deleted = 0
    
  3. 不需要了解業務場景,只需要改造的語句和改造之前的語句保持結果一致

  4. 現有索引可以滿足,不需要建索引

  5. 用改造後的語句實驗一下,只需要10ms 降低了近200倍!

    +----+--------------+------------+--------+---------------------------------+-------------------+---------+-----------------------+------+-------------+
    | id | select_type  | table      | type   | possible_keys                   | key               | key_len | ref                   | rows | Extra       |
    +----+--------------+------------+--------+---------------------------------+-------------------+---------+-----------------------+------+-------------+
    |  1 | PRIMARY      | cl         | range  | cm_log_cls_id,idx_last_upd_date | idx_last_upd_date | 8       | NULL                  |  379 | Using where |
    |  1 | PRIMARY      | emp        | eq_ref | PRIMARY                         | PRIMARY           | 4       | meituanorg.cl.ref_oid |    1 | Using where |
    |  2 | UNION        | cl         | range  | cm_log_cls_id,idx_last_upd_date | idx_last_upd_date | 8       | NULL                  |  379 | Using where |
    |  2 | UNION        | ec         | eq_ref | PRIMARY,emp_certificate_empid   | PRIMARY           | 4       | meituanorg.cl.ref_oid |    1 |             |
    |  2 | UNION        | emp        | eq_ref | PRIMARY                         | PRIMARY           | 4       | meituanorg.ec.emp_id  |    1 | Using where |
    | NULL | UNION RESULT | <union1,2> | ALL    | NULL                            | NULL              | NULL    | NULL                  | NULL |             |
    +----+--------------+------------+--------+---------------------------------+-------------------+---------+-----------------------+------+-------------+
    53 rows in set (0.01 sec)
    

明確應用場景

舉這個例子的目的在於顛覆我們對列的區分度的認知,一般上我們認為區分度越高的列,越容易鎖定更少的記錄,但在一些特殊的情況下,這種理論是有侷限性的。

select
   * 
from
   stage_poi sp 
where
   sp.accurate_result=1 
   and (
      sp.sync_status=0 
      or sp.sync_status=2 
      or sp.sync_status=4
   );
  1. 先看看執行多長時間,951條資料6.22秒,真的很慢。

  2. 先explain,rows達到了361萬,type = ALL表明是全表掃描。

    +----+-------------+-------+------+---------------+------+---------+------+---------+-------------+
    | id | select_type | table | type | possible_keys | key  | key_len | ref  | rows    | Extra       |
    +----+-------------+-------+------+---------------+------+---------+------+---------+-------------+
    |  1 | SIMPLE      | sp    | ALL  | NULL          | NULL | NULL    | NULL | 3613155 | Using where |
    +----+-------------+-------+------+---------------+------+---------+------+---------+-------------+
    
    
  3. 所有欄位都應用查詢返回記錄數,因為是單表查詢 0已經做過了951條。

    看一下accurate_result = 1的記錄數:

    select count(*),accurate_result from stage_poi  group by accurate_result;
    +----------+-----------------+
    | count(*) | accurate_result |
    +----------+-----------------+
    |     1023 |              -1 |
    |  2114655 |               0 |
    |   972815 |               1 |
    +----------+-----------------+
    

    我們看到accurate_result這個欄位的區分度非常低,整個表只有-1,0,1三個值,加上索引也無法鎖定特別少量的資料。

    再看一下sync_status欄位的情況:

    select count(*),sync_status from stage_poi  group by sync_status;
    +----------+-------------+
    | count(*) | sync_status |
    +----------+-------------+
    |     3080 |           0 |
    |  3085413 |           3 |
    +----------+-------------+
    

    同樣的區分度也很低,根據理論,也不適合建立索引。

    問題分析到這,好像得出了這個表無法優化的結論,兩個列的區分度都很低,即便加上索引也只能適應這種情況,很難做普遍性的優化,比如當sync_status 0、3分佈的很平均,那麼鎖定記錄也是百萬級別的。

  4. 找業務方去溝通,看看使用場景。業務方是這麼來使用這個SQL語句的,每隔五分鐘會掃描符合條件的資料,處理完成後把sync_status這個欄位變成1,五分鐘符合條件的記錄數並不會太多,1000個左右。瞭解了業務方的使用場景後,優化這個SQL就變得簡單了,因為業務方保證了資料的不平衡,如果加上索引可以過濾掉絕大部分不需要的資料。

  5. 根據建立索引規則,使用如下語句建立索引

    alter table stage_poi add index idx_acc_status(accurate_result,sync_status);
    
  6. 觀察預期結果,發現只需要200ms,快了30多倍。

    952 rows in set (0.20 sec)
    

單表查詢相對來說比較好優化,大部分時候只需要把where條件裡面的欄位依照規則加上索引就好,如果只是這種“無腦”優化的話,顯然一些區分度非常低的列,不應該加索引的列也會被加上索引,這樣會對插入、更新效能造成嚴重的影響,同時也有可能影響其它的查詢語句。所以我們第4步調差SQL的使用場景非常關鍵,我們只有知道這個業務場景,才能更好地輔助我們更好的分析和優化查詢語句。

無法優化的語句

select
   c.id,
   c.name,
   c.position,
   c.sex,
   c.phone,
   c.office_phone,
   c.feature_info,
   c.birthday,
   c.creator_id,
   c.is_keyperson,
   c.giveup_reason,
   c.status,
   c.data_source,
   from_unixtime(c.created_time) as created_time,
   from_unixtime(c.last_modified) as last_modified,
   c.last_modified_user_id  
from
   contact c  
inner join
   contact_branch cb 
      on  c.id = cb.contact_id  
inner join
   branch_user bu 
      on  cb.branch_id = bu.branch_id 
      and bu.status in (
         1,
      2)  
   inner join
      org_emp_info oei 
         on  oei.data_id = bu.user_id 
         and oei.node_left >= 2875 
         and oei.node_right <= 10802 
         and oei.org_category = - 1  
   order by
      c.created_time desc  limit 0 ,
      10;
  1. 先看語句執行多長時間,10條記錄用了13秒,已經不可忍受。

  2. explain

    +----+-------------+-------+--------+-------------------------------------+-------------------------+---------+--------------------------+------+----------------------------------------------+
    | id | select_type | table | type   | possible_keys                       | key                     | key_len | ref                      | rows | Extra                                        |
    +----+-------------+-------+--------+-------------------------------------+-------------------------+---------+--------------------------+------+----------------------------------------------+
    |  1 | SIMPLE      | oei   | ref    | idx_category_left_right,idx_data_id | idx_category_left_right | 5       | const                    | 8849 | Using where; Using temporary; Using filesort |
    |  1 | SIMPLE      | bu    | ref    | PRIMARY,idx_userid_status           | idx_userid_status       | 4       | meituancrm.oei.data_id   |   76 | Using where; Using index                     |
    |  1 | SIMPLE      | cb    | ref    | idx_branch_id,idx_contact_branch_id | idx_branch_id           | 4       | meituancrm.bu.branch_id  |    1 |                                              |
    |  1 | SIMPLE      | c     | eq_ref | PRIMARY                             | PRIMARY                 | 108     | meituancrm.cb.contact_id |    1 |                                              |
    +----+-------------+-------+--------+-------------------------------------+-------------------------+---------+--------------------------+------+----------------------------------------------+
    

    從執行計劃上看,mysql先查org_emp_info表掃描8849記錄,再用索引idx_userid_status關聯branch_user表,再用索引idx_branch_id關聯contact_branch表,最後主鍵關聯contact表。

    rows返回的都非常少,看不到有什麼異常情況。我們在看一下語句,發現後面有order by + limit組合,會不會是排序量太大搞的?於是我們簡化SQL,去掉後面的order by 和 limit,看看到底用了多少記錄來排序。

    select
      count(*)
    from
       contact c  
    inner join
       contact_branch cb 
          on  c.id = cb.contact_id  
    inner join
       branch_user bu 
          on  cb.branch_id = bu.branch_id 
          and bu.status in (
             1,
          2)  
       inner join
          org_emp_info oei 
             on  oei.data_id = bu.user_id 
             and oei.node_left >= 2875 
             and oei.node_right <= 10802 
             and oei.org_category = - 1  
    +----------+
    | count(*) |
    +----------+
    |   778878 |
    +----------+
    1 row in set (5.19 sec)
    

    發現排序之前居然鎖定了778878條記錄,如果針對70萬的結果集排序,將是災難性的,怪不得這麼慢,那我們能不能換個思路,先根據contact的created_time排序,再來join會不會比較快呢?

    於是改造成下面的語句,也可以用straight_join來優化:

    select
       c.id,
       c.name,
       c.position,
       c.sex,
       c.phone,
       c.office_phone,
       c.feature_info,
       c.birthday,
       c.creator_id,
       c.is_keyperson,
       c.giveup_reason,
       c.status,
       c.data_source,
       from_unixtime(c.created_time) as created_time,
       from_unixtime(c.last_modified) as last_modified,
       c.last_modified_user_id   
    from
       contact c  
    where
       exists (
          select
             1 
          from
             contact_branch cb  
          inner join
             branch_user bu        
                on  cb.branch_id = bu.branch_id        
                and bu.status in (
                   1,
                2)      
             inner join
                org_emp_info oei           
                   on  oei.data_id = bu.user_id           
                   and oei.node_left >= 2875           
                   and oei.node_right <= 10802           
                   and oei.org_category = - 1      
             where
                c.id = cb.contact_id    
          )    
       order by
          c.created_time desc  limit 0 ,
          10;
    

    驗證一下效果 預計在1ms內,提升了13000多倍!

    10 rows in set (0.00 sec)
    

    本以為至此大工告成,但我們在前面的分析中漏了一個細節,先排序再join和先join再排序理論上開銷是一樣的,為何提升這麼多是因為有一個limit!大致執行過程是:mysql先按索引排序得到前10條記錄,然後再去join過濾,當發現不夠10條的時候,再次去10條,再次join,這顯然在內層join過濾的資料非常多的時候,將是災難的,極端情況,內層一條資料都找不到,mysql還傻乎乎的每次取10條,幾乎遍歷了這個資料表!

    用不同引數的SQL試驗下:

    select
       sql_no_cache   c.id,
       c.name,
       c.position,
       c.sex,
       c.phone,
       c.office_phone,
       c.feature_info,
       c.birthday,
       c.creator_id,
       c.is_keyperson,
       c.giveup_reason,
       c.status,
       c.data_source,
       from_unixtime(c.created_time) as created_time,
       from_unixtime(c.last_modified) as last_modified,
       c.last_modified_user_id    
    from
       contact c   
    where
       exists (
          select
             1        
          from
             contact_branch cb         
          inner join
             branch_user bu                     
                on  cb.branch_id = bu.branch_id                     
                and bu.status in (
                   1,
                2)                
             inner join
                org_emp_info oei                           
                   on  oei.data_id = bu.user_id                           
                   and oei.node_left >= 2875                           
                   and oei.node_right <= 2875                           
                   and oei.org_category = - 1                
             where
                c.id = cb.contact_id           
          )        
       order by
          c.created_time desc  limit 0 ,
          10;
    Empty set (2 min 18.99 sec)
    

    2min 18.99 sec!比之前的情況還糟糕很多。由於mysql的nested loop機制,遇到這種情況,基本是無法優化的。這條語句最終也只能交給應用系統去優化自己的邏輯了。

通過這個例子我們可以看到,並不是所有語句都能優化,而往往我們優化時,由於SQL用例迴歸時落掉一些極端情況,會造成比原來還嚴重的後果。所以

  • 不要指望所有語句都能通過SQL優化
  • 不要過於自信,只針對具體case來優化,而忽略了更復雜的情況。

任何資料庫層面的優化都抵不上應用系統的優化