Effective MySQL 语句最优化 笔记

1、select * from table\G  返回结果垂直显示

 

2、查询表信息: show table status like 'testtable'\G

 

*************************** 1. row ***************************
           Name: supplier
         Engine: InnoDB
        Version: 10
     Row_format: Compact
           Rows: 1
 Avg_row_length: 16384
    Data_length: 16384
Max_data_length: 0
   Index_length: 16384
      Data_free: 8388608
 Auto_increment: NULL
    Create_time: 2013-05-23 21:19:24
    Update_time: NULL
     Check_time: NULL
      Collation: utf8_general_ci
       Checksum: NULL
 Create_options:
        Comment:
1 row in set (0.00 sec)

 

3. show create table test_table\G 查看建表信息

*************************** 1. row ***************************
       Table: supplier
Create Table: CREATE TABLE `supplier` (
  `name` varchar(32) DEFAULT NULL,
  `person` varchar(32) DEFAULT NULL,
  `tel` varchar(32) DEFAULT NULL,
  `phone` varchar(32) DEFAULT NULL,
  `location` varchar(64) DEFAULT NULL,
  KEY `name` (`name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
1 row in set (0.00 sec)

4、B-数适合直接查找,而散列适合一定范围的查找

 

5、alter table supplier add index index_name(name,location);

创建多列索引增加查询效率

 

6、show full processlist;查看当前进程

*************************** 1. row ***************************
     Id: 31
   User: root
   Host: localhost:4665
     db: bookshop
Command: Query
   Time: 0
  State: NULL
   Info: show full processlist
*************************** 2. row ***************************
     Id: 32
   User: root
   Host: localhost:30657
     db: neil
Command: Sleep
   Time: 78
  State:
   Info: NULL
2 rows in set (0.00 sec)

 

7、索引性能优化:

(1)整合ddl语句,也就是讲多条对同一表的alter 合并到一条语句中

(2)去掉重复的索引

(3)删除不用的索引

8、数据类型

(1)除非确定一个列可能包含NULL(未知的值),否则最好定义为NOT NULL

(2)采用mysql提供的ENUM 比如('Male','Female') 优点:紧采用1个字节来存储255个不同的值、可读性强、隐含了检查限制

(3)删除重复的语句:

select name from supplier where id=1;

select name from supplier where id=2;

select name from supplier where id=3;

改为

select name from supplier where id in(1,2,3);

开启分析功能 set profiling=1;

select ...

show profiles;

 

9、explain 用于SQL查询计划(QEP),它的结果能让我们了解SQL优化器如何执行SQL语句,帮助做出最优决策

mysql> explain select * from supplier where num=2\G
*************************** 1. row ***************************
           id: 1
  select_type: SIMPLE
        table: swid
         type: const
possible_keys: PRIMARY
          key: PRIMARY
      key_len: 4
          ref: const
         rows: 1
        Extra:
1 row in set (0.00 sec)

 

其中rows表示的试图分析的累积结果集,因为通过possilbe_keys的索引来查询,所以效率很高,如果是非索引结果就要遍历表中全部结果(全表扫描)

 

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