【发布时间】:2014-04-04 22:37:44
【问题描述】:
我的 SQL 是
SELECT authors.*, COUNT(*) FROM authors
INNER JOIN resources_authors ON authors.author_id=resources_authors.author_id
WHERE
resource_id IN
(SELECT resource_id FROM resources_authors WHERE author_id = '1313')
AND authors.author_id != '1313'
GROUP BY authors.author_id`
我对查询中的所有字段都有索引,但我仍然得到Using temporary; Using Filesort。
id select_type table type possible_keys key key_len ref rows Extra
1 PRIMARY authors ALL PRIMARY NULL NULL NULL 16025 Using where; Using temporary; Using filesort
1 PRIMARY resources_authors ref author_id author_id 4 authors.author_id 3 Using where
2 DEPENDENT SUBQUERY resources_authors unique_subquery resource_id,author_id,resource_id_2 resource_id 156 func,const 1 Using index; Using where
如何改进我的查询或表结构以加快查询速度?
这里有一个 SQL Fiddle,如果你想试验一下:http://sqlfiddle.com/#!2/96d57/2/0
【问题讨论】:
-
我认为
author_id != 1313不能有效利用索引。 -
@MKhalidJunaid - 这行不通,因为永远不会返回任何结果。
-
为什么说id必须是1313,然后说不是=1313? ...基本上你是说在资源作者是 1313 而作者不是 1313 的地方拉出来
-
@JohnRuddell - 这是书籍和作者之间的多对多关系(所以每本书可以有很多作者,每个作者可能写很多书)。子查询按作者 1313 查找所有书籍。主查询查找所有(共同)编写这些书籍的作者,但不包括原作者,因为他不需要。
-
好的,感谢您的澄清。
标签: mysql join query-optimization