清单 1. MySQL 慢查询日志

/usr/local/mysql/bin/mysqld, Version: 5.1.49-log, started with:

Tcp port: 3306 Unix socket: /tmp/mysql.sock

Time Id Command Argument

# Time: 030207 15:03:33

# User@Host: user[user] @ localhost.localdomain [127.0.0.1]

# Query_time: 13 Lock_time: 0 Rows_sent: 117 Rows_examined: 234

use sugarcrm;

select * from accounts inner join leads on accounts.id = leads.account_id;

我们想要考虑的关键对象是 Query_time,显示查询需要的时间。另一项要考虑的是 Rows_sent 和 Rows_examined 的数量,因为这些可指这样的情况:其中如果一个查询察看太多行或返回太多行,就会被错误地书写。您可以更深入地钻研如何写查询,即在查询开始处加上 EXPLAIN,它会返回查询计划,而非结果集,如清单 2 所示。

清单 2. MySQL EXPLAIN 结果

mysql> explain select * from accounts inner join leads on accounts.id = leads.account_id;

+----+-------------+----------+--------+--------------------------+---------+---

| id | select_type | table | type | possible_keys

| key | key_len | ref | rows | Extra |

+----+-------------+----------+--------+--------------------------+---------+--------

| 1 | SIMPLE | leads | ALL | idx_leads_acct_del | NULL | NULL

| NULL | 200 | |

| 1 | SIMPLE | accounts | eq_ref | PRIMARY,idx_accnt_id_del | PRIMARY | 108

| sugarcrm.leads.account_id | 1 | |

+----+-------------+----------+--------+--------------------------+---------+---------

2 rows in set (0.00 sec)

MySQL 手册更深入探究 EXPLAIN 输出的主题(参见 参考资料),但是我考虑的一项重要内容是 ‘type’ 列为 ‘ALL’ 的地方,因为这需要 MySQL 做一个全表扫描,且不需要键来执行查询。这些帮助您在添加索引时会大幅提高查询速度。


相关内容