添加mysql索引的3條原則

來源:互聯網
上載者:User

  一,索引的重要性

  索引用於快速找出在某個列中有一特定值的行。不使用索引,MySQL必須從第1條記錄開始然後讀完整個表直到找出相關的行。表越大,花費的時間越多。如果表中查詢的列有一個索引,MySQL能快速到達一個位置去搜尋到資料檔案的中間,沒有必要看所有資料。注意如果你需要訪問大部分行,順序讀取要快得多,因為此時我們避免磁碟搜尋。

  假如你用新華字典來尋找“張”這個漢字,不使用目錄的話,你可能要從新華字典的第一頁找到最後一頁,可能要花二個小時。字典越厚呢,你花的時間就越多。現在你使用目錄來尋找“張”這個漢字,張的首字母是z,z開頭的漢字從900多頁開始,有了這條線索,你尋找一個漢字可能只要一分鐘,由此可見索引的重要性。但是索引建的是不是越多越好呢,當然不是,如果一本書的目錄分成好幾級的話,我想你也會暈的。

  二,準備工作

 
  1. //準備二張測試表     
  2. mysql> CREATE TABLE `test_t` (     
  3.  ->   `id` int(11) NOT NULL auto_increment,     
  4.  ->   `num` int(11) NOT NULL default '0',     
  5.  ->   `d_num` varchar(30) NOT NULL default '0',     
  6.  ->   PRIMARY KEY  (`id`)     
  7.  -> ) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;     
  8. Query OK, 0 rows affected (0.05 sec)     
  9.     
  10. mysql> CREATE TABLE `test_test` (     
  11.  ->   `id` int(11) NOT NULL auto_increment,     
  12.  ->   `num` int(11) NOT NULL default '0',     
  13.  ->   PRIMARY KEY  (`id`)     
  14.  -> ) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;     
  15. Query OK, 0 rows affected (0.05 sec)       
  16.     
  17. //建立一個預存程序,為插資料方便     
  18. mysql> delimiter      
  19. mysql> create procedure i_test(pa int(11),tab varchar(30))     
  20.  -> begin     
  21.  ->     declare max_num int(11) default 100000;     
  22.  ->     declare i int default 0;     
  23.  ->     declare rand_num int;     
  24.  ->  declare double_num char;     
  25.  ->     
  26.  ->  if tab != 'test_test' then     
  27.  ->         select count(id) into max_num from test_t;     
  28.  ->         while i < pa do    
  29.  ->             if max_num < 100000 then     
  30.  ->                 select cast(rand()*100 as unsigned) into rand_num;     
  31.  ->                 select concat(rand_num,rand_num) into double_num;     
  32.  ->                 insert into test_t(num,d_num)values(rand_num,double_num);     
  33.  ->             end if;     
  34.  ->             set i = i +1;     
  35.  ->         end while;     
  36.  ->  else    
  37.  ->         select count(id) into max_num from test_test;     
  38.  ->         while i < pa do    
  39.  ->             if max_num < 100000 then     
  40.  ->                 select cast(rand()*100 as unsigned) into rand_num;     
  41.  ->                 insert into test_test(num)values(rand_num);     
  42.  ->             end if;     
  43.  ->             set i = i +1;     
  44.  ->         end while;     
  45.  ->  end if;     
  46.  -> end     
  47. Query OK, 0 rows affected (0.00 sec)     
  48.     
  49. mysql> delimiter ;     
  50. mysql> show variables like "%pro%";   //查看一下,記錄執行的profiling是不是開啟動了,預設是不開啟的     
  51. +---------------------------+-------+     
  52.  Variable_name              Value      
  53. +---------------------------+-------+     
  54.  profiling                  OFF        
  55.  profiling_history_size     15         
  56.  protocol_version           10         
  57.  slave_compressed_protocol  OFF        
  58. +---------------------------+-------+     
  59. 4 rows in set (0.00 sec)       
  60.     
  61. mysql> set profiling=1;           //開啟後,是為了對比加了索引後的執行時間     
  62. Query OK, 0 rows affected (0.00 sec)  

  三,執行個體

  1,單表資料太少,索引反而會影響速度

 
  1. mysql> call i_test(10,'test_t');    //向test_t表插入10條件     
  2. Query OK, 1 row affected (0.02 sec)     
  3.     
  4. mysql> select num from test_t where num!=0;     
  5. mysql> explain select num from test_t where num!=0\G;     
  6. *************************** 1. row ***************************     
  7.  id: 1     
  8.  select_type: SIMPLE     
  9.  table: test_t     
  10.  type: ALL     
  11.  possible_keys: NULL     
  12.  key: NULL     
  13.  key_len: NULL     
  14.  ref: NULL     
  15.  rows: 10     
  16.  Extra: Using where     
  17. 1 row in set (0.00 sec)     
  18.     
  19. ERROR:     
  20. No query specified     
  21.     
  22. mysql> create index num_2 on test_t (num);     
  23. Query OK, 10 rows affected (0.19 sec)     
  24. Records: 10  Duplicates: 0  Warnings: 0     
  25.     
  26. mysql> select num from test_t where num!=0;     
  27.     
  28. mysql> explain select num from test_t where num!=0\G;     
  29. *************************** 1. row ***************************     
  30.  id: 1     
  31.  select_type: SIMPLE     
  32.  table: test_t     
  33.  type: index     
  34.  possible_keys: num_2     
  35.  key: num_2     
  36.  key_len: 4     
  37.  ref: NULL     
  38.  rows: 10     
  39.  Extra: Using where; Using index     
  40. 1 row in set (0.00 sec)     
  41.     
  42. ERROR:     
  43. No query specified     
  44.     
  45. mysql> show profiles;     
  46. +----------+------------+---------------------------------------------+     
  47.  Query_ID  Duration    Query                                            
  48. +----------+------------+---------------------------------------------+     
  49.         1  0.00286325  call i_test(10,'test_t')                        //插入十條資料     
  50.         2  0.00026350  select num from test_t where num!=0              
  51.         3  0.00022250  explain select num from test_t where num!=0      
  52.         4  0.18385400  create index num_2 on test_t (num)              //建立索引     
  53.         5  0.00127525  select num from test_t where num!=0             //使用索引後,差不多是沒有使用索引的0.2倍     
  54.         6  0.00024375  explain select num from test_t where num!=0      
  55. +----------+------------+---------------------------------------------+     
  56. 6 rows in set (0.00 sec)   

  解釋:

  id:表示sql執行的順序

  select_type:SIMPLE,PRIMARY,UNION,DEPENDENT UNION,UNION RESULT,SUBQUERY,DEPENDENT SUBQUERY,DERIVED不同的查詢語句會有不同的select_type

  table:表示尋找的表名

  type:表示使用索引類型,或者有無使用索引.效率從高到低const、eq_reg、ref、range、index和ALL,其實這個根你sql的寫法有直接關係,例如:能用主鍵就用主鍵,where後面的條件加上索引,如果是唯一加上唯一索引等

  possible_keys:可能存在的索引

  key:使用索引

  key_len:使用索引的長度

  ref:使用哪個列或常數與key一起從表中選擇行,一般在多表聯集查詢時會有。

  rows:尋找出的行數

  Extra:額外說明

  前段時間寫過一篇博文mysql distinct和group by誰更好,裡面有朋友留言,說測試結果根我當時做的測試結果不一樣,當時我打比方解釋了一下,今天有時間,以例子的形勢,更直觀的表達出索引的工作原理。

  2,where後的條件,order by ,group by 等這樣過濾時,後面的欄位最好加上索引。根據實際情況,選擇PRIMARY KEY、UNIQUE、INDEX等索引,但是不是越多越好,要適度。

  3,聯集查詢,子查詢等多表操作時關連欄位要加索引

 
  1. mysql> call i_test(10,'test_test');    //向test_test表插入10條資料     
  2. Query OK, 1 row affected (0.02 sec)     
  3.     
  4. mysql> explain select a.num as num1,b.num as num2 from test_t as a left join tes     
  5. t_test as b on a.num=b.num\G;     
  6. *************************** 1. row ***************************     
  7.  id: 1     
  8.  select_type: SIMPLE     
  9.  table: a     
  10.  type: index     
  11.  possible_keys: NULL     
  12.  key: num_2     
  13.  key_len: 4     
  14.  ref: NULL     
  15.  rows: 10     
  16.  Extra: Using index     
  17. *************************** 2. row ***************************     
  18.  id: 1     
  19.  select_type: SIMPLE     
  20.  table: b     
  21.  type: ref     
  22.  possible_keys: num_1     
  23.  key: num_1     
  24.  key_len: 4     
  25.  ref: bak_test.a.num   //bak_test是資料庫名,a.num是test_t的一個欄位     
  26.  rows: 1080     
  27.  Extra: Using index     
  28. 2 rows in set (0.01 sec)     
  29.     
  30. ERROR:     
  31. No query specified   

  資料量特別大的時候,最好不要用聯集查詢,即使你做了索引。

  上面只是個人的一點小結,拋磚引玉一下。




聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.