当我执行以下查询时,我有几个表连接在一起:
SELECT article.year, authors.last_name, count(DISTINCT article.id) as count FROM
article LEFT JOIN authors ON article.id = authors.id WHERE authors.last_name =
'bloggs' GROUP BY article.year由于某些原因,返回结果需要6到7秒,考虑到它需要处理的行数相对较少,这对我来说似乎是令人难以置信的慢。我是不是做错了什么?
如果我对查询运行EXPLAIN,我会得到以下结果:
select_type table type possible_keys key key_len ref rows extra
=====================================================================================
simple article all null null null null 762 using temporary; using filesort
simple authors all null null null null 5061 using where; using join buffer这两个表都是InnoDB。我在我的本地机器上运行这个程序,这是相当低的规格(windows xp,1 ghz,1 1gb内存),但即便如此,我也会认为这会更快。如果我将更多的行加载到表中,则开始需要几分钟而不是几秒钟。
有什么想法吗?
表结构如下:
Article:
field type null key default extra
=======================================================
id int yes null
year char(20) yes null
volume char(20) yes null
issue char(20) yes null
title text yes null
Authors:
field type null key default extra
=======================================================
id int yes null
last_name char(100) yes null
initials char(10) yes null发布于 2011-10-07 16:35:43
尝试在列authors.last_name和authors.id上添加索引。
但是,你确定你的查询是正确的吗?它不应该看起来像是:
SELECT article.year, authors.last_name, count(DISTINCT article.id) as count FROM
article LEFT JOIN authors ON article.author_id = authors.id WHERE authors.last_name =
'bloggs' GROUP BY article.year如果是这样的话,将需要articles.author_id上的索引-虽然不是为了这个查询,但作为一般的最佳实践
发布于 2011-10-07 16:53:49
正如都铎所说,添加索引。还可以提取group by。
SELECT * FROM (SELECT article.year, authors.last_name, count(DISTINCT article.id) as count FROM
article LEFT JOIN authors ON article.author_id = authors.id WHERE authors.last_name =
'bloggs') GROUP BY article.year这样做,您首先通过连接获取,并在集合中应用聚合函数。
和explain来看看改进的地方在哪里。
建议的字体:
https://stackoverflow.com/questions/7684743
复制相似问题