优化SQL语句的一般步骤

数据库 MySQL
慢查询日志在查询结束以后才记录,所以在应用反映执行效率出现问题的时候慢查询日志并不能定位问题,可以使用 show processlist 命令查看当前 mysql 在进行的线程,包括线程的状态、是否锁表等,可以实时的查看 sql 的执行情况,同时对一些锁表操作进行优化。

[[201750]]

一、通过 show status 命令了解各种 sql 的执行频率

mysql 客户端连接成功后,通过 show [session|global] status 命令可以提供服务器状态信息,也可以在操作系统上使用 mysqladmin extend-status 命令获取这些消息。

show status 命令中间可以加入选项 session(默认) 或 global:

  • session (当前连接)
  • global (自数据上次启动至今)
  1. # Com_xxx 表示每个 xxx 语句执行的次数。 
  2. mysql> show status like 'Com_%'

 

我们通常比较关心的是以下几个统计参数:

  • Com_select : 执行 select 操作的次数,一次查询只累加 1。
  • Com_insert : 执行 insert 操作的次数,对于批量插入的 insert 操作,只累加一次。
  • Com_update : 执行 update 操作的次数。
  • Com_delete : 执行 delete 操作的次数。

上面这些参数对于所有存储引擎的表操作都会进行累计。下面这几个参数只是针对 innodb 的,累加的算法也略有不同:

  • Innodb_rows_read : select 查询返回的行数。
  • Innodb_rows_inserted : 执行 insert 操作插入的行数。
  • Innodb_rows_updated : 执行 update 操作更新的行数。
  • Innodb_rows_deleted : 执行 delete 操作删除的行数。

通过以上几个参数,可以很容易地了解当前数据库的应用是以插入更新为主还是以查询操作为主,以及各种类型的 sql 大致的执行比例是多少。对于更新操作的计数,是对执行次数的计数,不论提交还是回滚都会进行累加。

对于事务型的应用,通过 Com_commit 和 Com_rollback 可以了解事务提交和回滚的情况,对于回滚操作非常频繁的数据库,可能意味着应用编写存在问题。

此外,以下几个参数便于用户了解数据库的基本情况:

  • Connections : 试图连接 mysql 服务器的次数。
  • Uptime : 服务器工作时间。
  • Slow_queries : 慢查询次数。

二、定义执行效率较低的 sql 语句

1. 通过慢查询日志定位那些执行效率较低的 sql 语句,用 --log-slow-queries[=file_name] 选项启动时,mysqld 写一个包含所有执行时间超过 long_query_time 秒的 sql 语句的日志文件。

2. 慢查询日志在查询结束以后才记录,所以在应用反映执行效率出现问题的时候慢查询日志并不能定位问题,可以使用 show processlist 命令查看当前 mysql 在进行的线程,包括线程的状态、是否锁表等,可以实时的查看 sql 的执行情况,同时对一些锁表操作进行优化。

三、通过 explain 分析低效 sql 的执行计划

测试数据库地址:https://downloads.mysql.com/d...

统计某个 email 为租赁电影拷贝所支付的总金额,需要关联客户表 customer 和 付款表 payment , 并且对付款金额 amount 字段做求和(sum) 操作,相应的执行计划如下:

  1. mysql> explain select sum(amount) from customer a , payment b where a.customer_id= b.customer_id and a.email='JANE.BENNETT@sakilacustomer.org'\G   
  2.  
  3. *************************** 1. row *************************** 
  4.            id: 1 
  5.   select_type: SIMPLE 
  6.         table: a 
  7.    partitions: NULL 
  8.          type: ALL 
  9. possible_keys: PRIMARY 
  10.           keyNULL 
  11.       key_len: NULL 
  12.           ref: NULL 
  13.          rows: 599 
  14.      filtered: 10.00 
  15.         Extra: Using where 
  16. *************************** 2. row *************************** 
  17.            id: 1 
  18.   select_type: SIMPLE 
  19.         table: b 
  20.    partitions: NULL 
  21.          type: ref 
  22. possible_keys: idx_fk_customer_id 
  23.           key: idx_fk_customer_id 
  24.       key_len: 2 
  25.           ref: sakila.a.customer_id 
  26.          rows: 26 
  27.      filtered: 100.00 
  28.         Extra: NULL 
  29. rows in set, 1 warning (0.00 sec) 

 

  • select_type: 表示 select 类型,常见的取值有:
    • simple:简单表,及不使用表连接或者子查询
    • primary:主查询,即外层的查询
    • union:union 中的第二个或后面的查询语句
    • subquery: 子查询中的***个 select
  • table : 输出结果集的表
  • type : 表示 mysql 在表中找到所需行的方式,或者叫访问类型,常见类型性能由差到***依次是:all、index、range、ref、eq_ref、const,system、null:

1. type=ALL,全表扫描,mysql 遍历全表来找到匹配的行:

  1. mysql> explain select * from film where rating > 9 \G 
  2.  
  3. *************************** 1. row *************************** 
  4.           id: 1 
  5.  select_type: SIMPLE 
  6.        table: film 
  7.   partitions: NULL 
  8.         type: ALL 
  9. possible_keys: NULL 
  10.          keyNULL 
  11.      key_len: NULL 
  12.          ref: NULL 
  13.         rows: 1000 
  14.     filtered: 33.33 
  15.        Extra: Using where 
  16. 1 row in set, 1 warning (0.01 sec) 

 

2. type=index, 索引全扫描,mysql 遍历整个索引来查询匹配的行

  1. mysql> explain select title form film\G 
  2.  
  3. *************************** 1. row *************************** 
  4.           id: 1 
  5.  select_type: SIMPLE 
  6.        table: film 
  7.   partitions: NULL 
  8.         type: index 
  9. possible_keys: NULL 
  10.          key: idx_title 
  11.      key_len: 767 
  12.          ref: NULL 
  13.         rows: 1000 
  14.     filtered: 100.00 
  15.        Extra: Using index 
  16. 1 row in set, 1 warning (0.00 sec) 

 

3. type=range,索引范围扫描,常见于<、<=、>、>=、between等操作:

  1. mysql> explain select * from payment where customer_id >= 300 and customer_id <= 350 \G   
  2.  
  3. *************************** 1. row *************************** 
  4.           id: 1 
  5.  select_type: SIMPLE 
  6.        table: payment 
  7.   partitions: NULL 
  8.         type: range 
  9. possible_keys: idx_fk_customer_id 
  10.          key: idx_fk_customer_id 
  11.      key_len: 2 
  12.          ref: NULL 
  13.         rows: 1350 
  14.     filtered: 100.00 
  15.        Extra: Using index condition 
  16. 1 row in set, 1 warning (0.07 sec) 

 

4. type=ref, 使用非唯一索引扫描或唯一索引的前缀扫描,返回匹配某个单独值的记录行,例如:

  1. mysql> explain select * from payment where customer_id = 350 \G   
  2. *************************** 1. row *************************** 
  3.           id: 1 
  4.  select_type: SIMPLE 
  5.        table: payment 
  6.   partitions: NULL 
  7.         type: ref 
  8. possible_keys: idx_fk_customer_id 
  9.          key: idx_fk_customer_id 
  10.      key_len: 2 
  11.          ref: const 
  12.         rows: 23 
  13.     filtered: 100.00 
  14.        Extra: NULL 
  15. 1 row in set, 1 warning (0.01 sec) 

 

索引 idx_fk_customer_id 是非唯一索引,查询条件为等值查询条件 customer_id = 350, 所以扫描索引的类型为 ref。ref 还经常出现在 join 操作中:

  1. mysql> explain select b.*, a.* from payment a,customer b where a.customer_id = b.customer_id \G  
  2.  
  3. *************************** 1. row *************************** 
  4.           id: 1 
  5.  select_type: SIMPLE 
  6.        table: b 
  7.   partitions: NULL 
  8.         type: ALL 
  9. possible_keys: PRIMARY 
  10.          keyNULL 
  11.      key_len: NULL 
  12.          ref: NULL 
  13.         rows: 599 
  14.     filtered: 100.00 
  15.        Extra: NULL 
  16. *************************** 2. row *************************** 
  17.           id: 1 
  18.  select_type: SIMPLE 
  19.        table: a 
  20.   partitions: NULL 
  21.         type: ref 
  22. possible_keys: idx_fk_customer_id 
  23.          key: idx_fk_customer_id 
  24.      key_len: 2 
  25.          ref: sakila.b.customer_id 
  26.         rows: 26 
  27.     filtered: 100.00 
  28.        Extra: NULL 
  29. rows in set, 1 warning (0.00 sec) 

 

5. type=eq_ref,类似 ref,区别就在使用的索引时唯一索引,对于每个索引的键值,表中只要一条记录匹配;简单的说,就是多表连接中使用 primary key 或者 unique index 作为关联条件。

  1. mysql> explain select * from film a , film_text b where a.film_id = b.film_id \G 
  2.  
  3. *************************** 1. row *************************** 
  4.           id: 1 
  5.  select_type: SIMPLE 
  6.        table: b 
  7.   partitions: NULL 
  8.         type: ALL 
  9. possible_keys: PRIMARY 
  10.          keyNULL 
  11.      key_len: NULL 
  12.          ref: NULL 
  13.         rows: 1000 
  14.     filtered: 100.00 
  15.        Extra: NULL 
  16. *************************** 2. row *************************** 
  17.           id: 1 
  18.  select_type: SIMPLE 
  19.        table: a 
  20.   partitions: NULL 
  21.         type: eq_ref 
  22. possible_keys: PRIMARY 
  23.          keyPRIMARY 
  24.      key_len: 2 
  25.          ref: sakila.b.film_id 
  26.         rows: 1 
  27.     filtered: 100.00 
  28.        Extra: Using where 
  29. rows in set, 1 warning (0.03 sec) 

 

6. type=const/system,单表中最多有一个匹配行,查起来非常迅速,所以这个匹配行中的其他列的值可以被优化器在当前查询中当作常量来处理,例如,根据主键 primary key 或者唯一索引 unique index 进行查询。

  1. mysql> create table test_const ( 
  2.    ->         test_id int
  3.    ->         test_context varchar(10), 
  4.    ->         primary key (`test_id`), 
  5.    ->     ); 
  6.     
  7. insert into test_const values(1,'hello'); 
  8.  
  9. explain select * from ( select * from test_const where test_id=1 ) a \G 
  10. *************************** 1. row *************************** 
  11.           id: 1 
  12.  select_type: SIMPLE 
  13.        table: test_const 
  14.   partitions: NULL 
  15.         type: const 
  16. possible_keys: PRIMARY 
  17.          keyPRIMARY 
  18.      key_len: 4 
  19.          ref: const 
  20.         rows: 1 
  21.     filtered: 100.00 
  22.        Extra: NULL 
  23.  1 row in set, 1 warning (0.00 sec) 

 

7. type=null, mysql 不用访问表或者索引,直接就能够得到结果:

  1. mysql> explain select 1 from dual where 1 \G 
  2. *************************** 1. row *************************** 
  3.           id: 1 
  4.  select_type: SIMPLE 
  5.        tableNULL 
  6.   partitions: NULL 
  7.         type: NULL 
  8. possible_keys: NULL 
  9.          keyNULL 
  10.      key_len: NULL 
  11.          ref: NULL 
  12.         rowsNULL 
  13.     filtered: NULL 
  14.        Extra: No tables used 
  15. 1 row in set, 1 warning (0.00 sec) 

 

类型 type 还有其他值,如 ref_or_null (与 ref 类似,区别在于条件中包含对 null 的查询)、index_merge(索引合并优化)、unique_subquery (in 的后面是一个查询主键字段的子查询)、index_subquery(与 unique_subquery 类似,区别在于 in 的后面是查询非唯一索引字段的子查询)等。

  • possible_keys : 表示查询时可能使用的索引。
  • key :表示实际使用索引
  • key-len : 使用到索引字段的长度。
  • rows : 扫描行的数量
  • extra:执行情况的说明和描述,包含不适合在其他列中显示但是对执行计划非常重要的额外信息。

show warnings 命令

执行explain 后再执行 show warnings,可以看到sql 真正被执行之前优化器做了哪些 sql 改写:

  1. MySQL [sakila]> explain select sum(amount) from customer a , payment b where 1=1 and a.customer_id = b.customer_id and email = 'JANE.BENNETT@sakilacustomer.org'\G 
  2. *************************** 1. row *************************** 
  3.            id: 1 
  4.   select_type: SIMPLE 
  5.         table: a 
  6.    partitions: NULL 
  7.          type: ALL 
  8. possible_keys: PRIMARY 
  9.           keyNULL 
  10.       key_len: NULL 
  11.           ref: NULL 
  12.          rows: 599 
  13.      filtered: 10.00 
  14.         Extra: Using where 
  15. *************************** 2. row *************************** 
  16.            id: 1 
  17.   select_type: SIMPLE 
  18.         table: b 
  19.    partitions: NULL 
  20.          type: ref 
  21. possible_keys: idx_fk_customer_id 
  22.           key: idx_fk_customer_id 
  23.       key_len: 2 
  24.           ref: sakila.a.customer_id 
  25.          rows: 26 
  26.      filtered: 100.00 
  27.         Extra: NULL 
  28. rows in set, 1 warning (0.00 sec) 
  29.  
  30. MySQL [sakila]> show warnings; 
  31. +-------+------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ 
  32. Level | Code | Message                                                                                                                                                                                                                                                     | 
  33. +-------+------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ 
  34. | Note  | 1003 | /* select#1 */ select sum(`sakila`.`b`.`amount`) AS `sum(amount)` from `sakila`.`customer` `a` join `sakila`.`payment` `b` where ((`sakila`.`b`.`customer_id` = `sakila`.`a`.`customer_id`) and (`sakila`.`a`.`email` = 'JANE.BENNETT@sakilacustomer.org')) | 
  35. +-------+------+-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ 
  36. 1 row in set (0.00 sec) 

 

从 warning 的 message 字段中能够看到优化器自动去除了 1=1 恒成立的条件,也就是说优化器在改写 sql 时会自动去掉恒成立的条件。

explain 命令也有对分区的支持.

  1. MySQL [sakila]> CREATE TABLE `customer_part` ( 
  2.     ->   `customer_id` smallint(5) unsigned NOT NULL AUTO_INCREMENT, 
  3.     ->   `store_id` tinyint(3) unsigned NOT NULL
  4.     ->   `first_name` varchar(45) NOT NULL
  5.     ->   `last_name` varchar(45) NOT NULL
  6.     ->   `email` varchar(50) DEFAULT NULL
  7.     ->   `address_id` smallint(5) unsigned NOT NULL
  8.     ->   `active` tinyint(1) NOT NULL DEFAULT '1'
  9.     ->   `create_date` datetime NOT NULL
  10.     ->   `last_update` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
  11.     ->   PRIMARY KEY (`customer_id`) 
  12.     ->   
  13.     -> ) partition by hash (customer_id) partitions 8; 
  14. Query OK, 0 rows affected (0.06 sec) 
  15.  
  16. MySQL [sakila]> insert into customer_part select * from customer; 
  17. Query OK, 599 rows affected (0.06 sec) 
  18. Records: 599  Duplicates: 0  Warnings: 0 
  19.  
  20. MySQL [sakila]> explain select * from customer_part where customer_id=130\G 
  21. *************************** 1. row *************************** 
  22.            id: 1 
  23.   select_type: SIMPLE 
  24.         table: customer_part 
  25.    partitions: p2 
  26.          type: const 
  27. possible_keys: PRIMARY 
  28.           keyPRIMARY 
  29.       key_len: 2 
  30.           ref: const 
  31.          rows: 1 
  32.      filtered: 100.00 
  33.         Extra: NULL 
  34. 1 row in set, 1 warnings (0.00 sec) 

 

可以看到 sql 访问的分区是 p2。

四、通过 performance_schema 分析 sql 性能

旧版本的 mysql 可以使用 profiles 分析 sql 性能,我用的是5.7.18的版本,已经不允许使用 profiles 了,推荐用

performance_schema 分析sql。

五、通过 trace 分析优化器如何选择执行计划。

mysql5.6 提供了对 sql 的跟踪 trace,可以进一步了解为什么优化器选择 A 执行计划而不是 B 执行计划,帮助我们更好的理解优化器的行为。

使用方式:首先打开 trace ,设置格式为 json,设置 trace ***能够使用的内存大小,避免解析过程中因为默认内存过小而不能够完整显示。

  1. MySQL [sakila]> set optimizer_trace="enabled=on",end_markers_in_json=on
  2. Query OK, 0 rows affected (0.00 sec) 
  3.  
  4. MySQL [sakila]> set optimizer_trace_max_mem_size=1000000; 
  5. Query OK, 0 rows affected (0.00 sec) 

 

接下来执行想做 trace 的 sql 语句,例如像了解租赁表 rental 中库存编号 inventory_id 为 4466 的电影拷贝在出租日期 rental_date 为 2005-05-25 4:00:00 ~ 5:00:00 之间出租的记录:

  1. mysql> select rental_id from rental where 1=1 and rental_date >= '2005-05-25 04:00:00' and rental_date <= '2005-05-25 05:00:00' and inventory_id=4466; 
  2. +-----------+ 
  3. | rental_id | 
  4. +-----------+ 
  5. |        39 | 
  6. +-----------+ 
  7. 1 row in set (0.06 sec) 
  8.  
  9. MySQL [sakila]> select * from information_schema.optimizer_trace\G 
  10. *************************** 1. row *************************** 
  11.                             QUERY: select * from infomation_schema.optimizer_trace 
  12.                             TRACE: { 
  13.   "steps": [ 
  14.   ] /* steps */ 
  15. MISSING_BYTES_BEYOND_MAX_MEM_SIZE: 0 
  16.           INSUFFICIENT_PRIVILEGES: 0 
  17. 1 row in set (0.00 sec) 

 

六、 确定问题并采取相应的优化措施

经过以上步骤,基本就可以确认问题出现的原因。此时可以根据情况采取相应的措施,进行优化以提高执行的效率。

 

责任编辑:庞桂玉 来源: segmentfault
相关推荐

2022-04-02 15:08:54

API调试

2011-04-06 16:41:25

LCPPPPIPCP

2010-05-14 14:12:58

MySQL数据库优化

2020-06-09 08:09:07

机器学习统计学习无监督学习

2011-09-08 11:35:18

2010-10-08 14:23:08

MySQL中INSER

2011-03-31 11:14:51

Sql语句优化

2010-04-13 15:04:16

Oracle优化

2021-08-16 08:42:31

MySQL查询数据库

2021-08-19 09:16:29

MySQL数据库优化器

2010-09-14 10:55:14

DIV CSS网页制作

2019-06-05 15:23:09

Redis缓存存储

2012-06-27 09:29:49

程序员

2018-01-08 15:07:15

java项目后台

2023-07-27 08:34:57

软件迭代管理

2010-11-04 15:39:40

DB2 SQL语句

2013-01-20 21:55:24

移动策略

2010-09-07 15:12:25

SQL语句优化

2009-11-06 17:13:24

Oracle SQL语

2010-03-31 09:51:38

CentOS系统
点赞
收藏

51CTO技术栈公众号