有两个表,表a
CREATE
TABLE
`a` (
`id` mediumint( 8 ) unsigned NOT NULL AUTO_INCREMENT,
`fid` smallint ( 6 ) unsigned NOT NULL DEFAULT ' 0 ' ,
`cnt` smallint ( 6 ) unsigned NOT NULL DEFAULT ' 0 ' ,
...
...
...
PRIMARY KEY (`id`),
KEY `idx_fid` (`fid`),
) ENGINE = MyISAM DEFAULT CHARSET = utf8
`id` mediumint( 8 ) unsigned NOT NULL AUTO_INCREMENT,
`fid` smallint ( 6 ) unsigned NOT NULL DEFAULT ' 0 ' ,
`cnt` smallint ( 6 ) unsigned NOT NULL DEFAULT ' 0 ' ,
...
...
...
PRIMARY KEY (`id`),
KEY `idx_fid` (`fid`),
) ENGINE = MyISAM DEFAULT CHARSET = utf8
表b
CREATE
TABLE
`b`
(`fid` smallint ( 6 ) unsigned NOT NULL AUTO_INCREMENT,
`name` char ( 50 ) NOT NULL DEFAULT '' ,
...
...
...
PRIMARY KEY (`fid`),
) ENGINE = MyISAM DEFAULT CHARSET = utf8
(`fid` smallint ( 6 ) unsigned NOT NULL AUTO_INCREMENT,
`name` char ( 50 ) NOT NULL DEFAULT '' ,
...
...
...
PRIMARY KEY (`fid`),
) ENGINE = MyISAM DEFAULT CHARSET = utf8
操作SQL如下:
SELECT
COUNT
(
*
)
AS
num1,
SUM
(a.cnt)
+
COUNT
(
*
)
AS
num2
FROM a, b
WHERE b.fid = ' 10913 ' AND a.fid = b.fid
FROM a, b
WHERE b.fid = ' 10913 ' AND a.fid = b.fid
我们先看下执行计划:
我们可以看到扫描行数是229049行,执行时间:
太可怕了,运行set profiling=1,让我们看看时间主要消耗在哪里?
sending data花费的时间较长,那这段时间到底是做什么的呢?先看下这个吧:http://renxijun.blog.sohu.com/82906360.html
意思是它在为select语句准备数据,解决办法:
建索引:
create
index
idx_fid_cnt
on
a (fid,cnt);
再看下,执行计划和执行时间:
总结:使用恰当的索引,是sql的效率倍增,类似sum的函数还有min(),max(),这些都需要在字段上建索引