查询性能优化
1 优化数据访问基本原则
应用程序只获得自己需要的数据,不应访问更多的行或列。
Mysql服务器不应分析超过需要的行。
查询如果向服务器请求了不需要的数据,就会消耗多余的CPU,内存,网络带宽等资源。
如无需使用select * from table等语句查询所有字段,而仅仅只指定需要的字段。
2 经常需要反省自己Mysql是否检索了太多的数据,其中可以指出开销的三个指标。
执行时间
检查行数
返回行数
这三个指标会被写入慢查询日志,作为大致反映Mysql在内部执行查询的时候要访问多少数据,以及查询时间等。
mysql> show index from test1\G;
Table: test1
Non_unique: 1
Key_name: a1
Seq_in_index: 1
Column_name: a1
Collation: A
Cardinality: 4
Sub_part: NULL
Packed: NULL
Null: YES
Index_type: BTREE
Comment:
1 row in set (0.00 sec)
*************************** 1. row ***************************
id: 1
select_type: SIMPLE
table: test1
type: ref
possible_keys: a1
key: a1
key_len: 5
ref: const
rows: 15
Extra: Using where; Using index
1 row in set (0.00 sec)
Query OK, 65537 rows affected (0.03 sec)
Records: 65537 Duplicates: 0 Warnings: 0
*************************** 1. row ***************************
id: 1
select_type: SIMPLE
table: test1
type: ALL
possible_keys: NULL
key: NULL
key_len: NULL
ref: NULL
rows: 65537
Extra: Using where
1 row in set (0.00 sec)