java 數據庫優化(一)

在我們書寫sql語句的時候,如果在數據量比較小的時候不會影響到query,但是,當數據量大的時候就要考慮如何快速的查詢數據; 下面介紹一些有用的技巧;
1 通過索引優化

select count(*) from orders where user_id like '100%';

這個sql是查詢訂單表裏面以100開頭的數據有多少;user_id 沒有添加索引;

alter table orders add index(user_id);
show profiles;(如果這個命令不懂的話請看上篇博客)

mysql> show profiles;
+----------+------------+-------------------------------------------------------+
| Query_ID | Duration   | Query                                                 |
+----------+------------+-------------------------------------------------------                        
|        1 | 0.00247375 | select count(*) from orders where user_id like "100%" |           
|        2 | 0.00142925 | select count(*) from orders where user_id like "100%" |
+----------+------------+-------------------------------------------------------+

分析:id爲1的是我們沒有add index時候查詢的,耗時0.00247375,2是add index是的用時0.00142925 ,算了一下,(247375 - 12925)/247375*100%=42.22%,效率提高了百分之40多,這就是添加索引的好處;但是,並不是所有的列都要添加索引,如果使用非常平凡的字段加上就可以了;那麼問題來了,我怎麼知道哪些列加了索引呢?

show index from tableName;

就能知道了;
2 很多人說,查詢一個字段和查詢這個字段所在的那條數據效率是一樣的,真的一樣嗎?下面我們試試;

(1)select * from orders where id = 10025;
 (2)select status from orders where id = 10025;

結果如下:

    32 | 0.00044925 | select user_id,phone,pwd,name,status from base_user where phone = 17742039272
  33 | 0.00089775 | select user_id,phone,pwd,name,status from base_user where phone = 17742039272
  34 | 0.00041275 | select user_id,phone,pwd,name,status from base_user where phone = 17742039272
  35 | 0.00039975 | select user_id,phone,pwd,name,status from base_user where phone = 17742039272
  36 | 0.00037925 | select user_id,phone,pwd,name,status from base_user where phone = 17742039272
  37 | 0.00038900 | select user_id,phone,pwd,name,status from base_user where phone = 17742039272
  38 | 0.00045800 | select * from base_user where phone = 17742039272
  39 | 0.00056800 | select * from base_user where phone = 17742039272
  40 | 0.00052150 | select * from base_user where phone = 17742039272
  41 | 0.00040925 | select * from base_user where phone = 17742039272
  42 | 0.00040975 | select phone from base_user where phone = 17742039272
  43 | 0.00041725 | select phone from base_user where phone = 17742039272
  44 | 0.00037500 | select phone from base_user where phone = 17742039272
  45 | 0.00048475 | select phone from base_user where phone = 17742039272
  46 | 0.00031375 | select phone from base_user where phone = 17742039272

分析:phone沒有添加索引,id爲37和38的都是查詢所有列,爲了數據準確,進行了多次查詢。明確的寫出所有列,平均耗時39518.75,這種耗時48918.75,查詢一個字段耗時40010,可以看出,使用 這種查詢的效率低(48918.75-(39518.75+40010)/2)/48918.75=18.71,也就是說如果明確的告訴mysql要查詢哪些列,效率可以提升20%;也可以得出,明確的寫出所有查詢列和查詢一列的效率基本是一樣的;

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章