superwei

          導航

          <2018年10月>
          30123456
          78910111213
          14151617181920
          21222324252627
          28293031123
          45678910

          統計

          常用鏈接

          留言簿(4)

          隨筆分類

          隨筆檔案

          文章分類

          文章檔案

          搜索

          最新評論

          閱讀排行榜

          評論排行榜

          【Mysql】關于索引

          DB引擎:InnoDB
          兩表A,B表均為6W+的記錄。用B表的信息更新A表。
          SQL:update A left join B on A.field1 = B.field1 and A.field2 = B.field2
                   set A.field3 = B.field3, A.field4 = B.field4
          無引擎時:每1000更新需要2分11秒,全部更新大概需要2~3小時。

          此時加入索引:
          CREATE INDEX field1_Index ON `A`(`field1`);
          注:1、此處只加field1是因為 field2的內容變化很小,就那幾個值。
                2、此SQL里的字段都不是主鍵

          再次執行SQL,效率依舊。似乎索引沒有作用。為了驗證我的想法,查看了執行方式:
          explain update A left join B on A.field1 = B.field1 and A.field2 = B.field2
                   set A.field3 = B.field3, A.field4 = B.field4 
          果然在執行時,沒用到索引。找到癥結,那就繼續找為什么索引沒有被用的原因。
          查找過程省略,直接上結果。
          因為是update,所以我認為 左聯和直聯,對于結果沒有區別,但是從左聯改為直聯后,
          再查詢執行方式,發現就能使用索引(原因暫不知道,以后知道了再寫)
          于是再次執行如下SQL:
          update A inner join B on A.field1 = B.field1 and A.field2 = B.field2
                   set A.field3 = B.field3, A.field4 = B.field4 
          6W+的數據執行時間:1.43秒
          優化完畢。
          另,因為以上字段都非主鍵,所以 SQL修改成以下方式執行似乎更快,查詢執行方式,用到了主鍵索引和我自己加的索引
          update A left join B on A.field1 = B.field1 and A.field2 = B.field2
                   set A.field3 = B.field3, A.field4 = B.field4
          where A.key in (select key from A)

          附:
          刪除索引:drop INDEX field1_Index ON `A`;
          查看索引:show index from A
          查看線程:select * from information_schema.processlist t
                        show processlist
          殺線程: kill processId


          posted on 2018-10-25 09:49 小辭猬 閱讀(176) 評論(0)  編輯  收藏


          只有注冊用戶登錄后才能發表評論。


          網站導航:
           
          主站蜘蛛池模板: 大方县| 旌德县| 嘉定区| 玉林市| 平阴县| 凉城县| 灌阳县| 凤城市| 宁阳县| 封开县| 石嘴山市| 象山县| 平潭县| 鱼台县| 郯城县| 宿迁市| 华亭县| 昆明市| 黄石市| 怀远县| 静乐县| 天津市| 荃湾区| 仁化县| 南漳县| 建平县| 阳东县| 白城市| 芦山县| 临汾市| 新郑市| 甘肃省| 成武县| 沅江市| 房产| 仁寿县| 囊谦县| 喀喇沁旗| 博爱县| 新蔡县| 洪江市|