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%;也可以得出,明确的写出所有查询列和查询一列的效率基本是一样的;

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