sql查詢優化是平常工做中必不可少的,整體的優化思想是儘量的減小IO操做和記錄掃描行數mysql
mysql> show variables like 'slow_query_log';sql
+----------------+-------+
| 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:\xampp\mysql\data\80CEAE742547827-slow.log |
+---------------------+----------------------------------------------+
2 rows in set (0.00 sec)優化
mysql> show variables like '%log_queries_not_using%';
+-------------------------------+-------+
| Variable_name | Value |
+-------------------------------+-------+
| log_queries_not_using_indexes | OFF |spa
+-------------------------------+-------+
1 row in set (0.00 sec)3d
mysql> set global log_queries_not_using_indexes=on;
Query OK, 0 rows affected (0.00 sec)日誌
mysql> show variables like '%long_query%';
+-----------------+-----------+
| Variable_name | Value |
+-----------------+-----------+
| long_query_time | 10.000000 |
+-----------------+-----------+
1 row in set (0.00 sec)code
mysql> set global long_query_time=1;
Query OK, 0 rows affected (0.00 sec)blog
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已是最優化了
優化前
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表沒有使用文件排序和臨時表
優化前
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之間的記錄就只有兩條了