MySQL的Explain命令用于查看执行效果。虽然这个命令只能搭配select类型语句使用,如果你想查看update,delete类型语句中的索引效果,也不是太难的事情,只要保持条件不变,把类型转换成select就行了。
explain的语法如下:
explain [extended] select ... from ... where ...
如果使用了extended,那么在执行完explain语句后,可以使用show warnings语句查询相应的优化信息。
mk-visual-explain工具扩展了explain,它提供了一种更直观的树形表现形式,使用方法很简单:
mk-visual-explain <file_containing_explain_output> mk-visual-explain -c <file_containing_query> mysql -e "explain select * from mysql.user" | mk-visual-explain
也可以在MySQL命令行里通过设置pager的方式来执行:
mysql> pager mk-visual-explain mysql> explain [extended] select ... from ... where ...
进入正题,为了让例子更具体化,我们先来建一个表,插入一点测试数据:
CREATE TABLE IF NOT EXISTS `article` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `author_id` int(10) unsigned NOT NULL, `category_id` int(10) unsigned NOT NULL, `views` int(10) unsigned NOT NULL, `comments` int(10) unsigned NOT NULL, `title` varbinary(255) NOT NULL, `content` text NOT NULL, PRIMARY KEY (`id`) ); INSERT INTO `article` (`author_id`, `category_id`, `views`, `comments`, `title`, `content`) VALUES (1, 1, 1, 1, ''1'', ''1''), (2, 2, 2, 2, ''2'', ''2'');
CREATE TABLE IF NOT EXISTS `article` ( `id` int(10) unsigned NOT NULL AUTO_INCREMENT, `author_id` int(10) unsigned NOT NULL, `category_id` int(10) unsigned NOT NULL, `views` int(10) unsigned NOT NULL, `comments` int(10) unsigned NOT NULL, `title` varbinary(255) NOT NULL, `content` text NOT NULL, PRIMARY KEY (`id`) );
INSERT INTO `article` (`author_id`, `category_id`, `views`, `comments`, `title`, `content`) VALUES (1, 1, 1, 1, ''1'', ''1''), (2, 2, 2, 2, ''2'', ''2'');
缺省只建了一个主键,没有建其他的索引。测试时,如果你时间充裕,应该尽可能插 |