sql及索引优化
sql查询优化是日常工作中必不可少的,总体的优化思想是尽可能的减少IO操作和记录扫描行数
开启慢查询日志
查看慢查询日志是否打开
mysql> show variables like 'slow_query_log';
+----------------+-------+
| Variable_name | Value |
+----------------+-------+
| slow_query_log | OFF |
+----------------+-------+
1 row in set (0.00 sec)
mysql> set global slow_query_log=on;
Query OK, 0 rows affected (0.05 sec)
慢查询日志文件存储位置
mysql> show variables like '%slow_query_log_file%';
+---------------------+----------------------------------------------+
| Variable_name | Value |
+---------------------+----------------------------------------------+
| slow_query_log_file | C:xamppmysqldata80CEAE742547827-slow.log |
+---------------------+----------------------------------------------+
2 rows in set (0.00 sec)
是否记录没有使用索引的sql
mysql> show variables like '%log_queries_not_using%';
+-------------------------------+-------+
| Variable_name | Value |
+-------------------------------+-------+
| log_queries_not_using_indexes | OFF |
+-------------------------------+-------+
1 row in set (0.00 sec)
mysql> set global log_queries_not_using_indexes=on;
Query OK, 0 rows affected (0.00 sec)
执行时间大于N秒的SQL会被记录
mysql> show variables like '%long_query%';
+-----------------+-----------+
| Variable_name | Value |
+-----------------+-----------+
| long_query_time | 10.000000 |
+-----------------+-----------+
1 row in set (0.00 sec)
mysql> set global long_query_time=1;
Query OK, 0 rows affected (0.00 sec)
max和count语句优化
max和min优化通过对需要求最大值和最小值的字段建立索引,看下面的例子
索引前
mysql> explain select max(payment_date) from payment G
*************************** 1. row ***************************
id: 1
select_type: SIMPLE
table: payment
type: ALL
possible_keys: NULL
key: NULL
key_len: NULL
ref: NULL
rows: 16086
Extra: NULL
1 row in set (0.00 sec)
mysql> create index ids_payment_date on payment(payment_date);
Query OK, 0 rows affected (0.30 sec)
Records: 0 Duplicates: 0 Warnings: 0
索引后
mysql> explain select max(payment_date) from payment G
*************************** 1. row ***************************
id: 1
select_type: SIMPLE
table: NULL
type: NULL
possible_keys: NULL
key: NULL
key_len: NULL
ref: NULL
rows: NULL
Extra: Select tables optimized away
1 row in set (0.00 sec)
Select tables optimized away表示sql已经是最优化了
group by语句优化
优化前
select actor.first_name, actor.last_name, count(*) from sakila.film_actor INNER JOIN sakila.actor USING(actor_id) GROUP BY film_actor.actor_id
使用join子查询的方式优化后,actor表没有在使用文件排序和临时表
优化后
select actor.first_name, actor.last_name, c.cnt from sakila.actor INNER JOIN ( select actor_id, count(*) as cnt from sakila.film_actor GROUP BY actor_id ) as c using(actor_id)
虽然优化后仍然扫描了200行的记录,但是actor表没有使用文件排序和临时表
limit查询优化
优化前
select film_id, description from sakila.film order by film_id limit 50, 5
优化后
select film_id, description from sakila.film where film_id > 50 and film_id <= 55 order by film_id limit 0, 5
从图中可以看出扫描记录数变成了5行,避免数据量大时扫描过多的记录
这中优化方法有个缺点,当记录是不连续的情况时,例如:删除51,52,53三条记录,这时50到55之间的记录就只有两条了