避免在查询中使用filesort

时间:2014-02-25 13:58:37

标签: mysql sql

我有两个表,帖子和posts_relationship。

posts:id, title, text, lang, timestamp

posts_relationship: id, post_id, subcategory_id

这是我的疑问:

SELECT  posts.title,
        posts.timestamp
  FROM  posts_relationship
   INNER JOIN posts ON posts.id = posts_relationship.post_id
  WHERE posts.lang = 'it' AND
        posts.timestamp <= NOW() AND 
        posts_relationship.subcategory_id = 21
  ORDER BY posts.timestamp DESC

我在posts.langposts.timestampposts_relationships.post_idposts_relationship.subcategory_id添加了索引。

但是通过解释我总是临时或文件。

我怎么才能只使用“在哪里”?

1 个答案:

答案 0 :(得分:0)

我不清楚这条线路在做什么:

    posts.timestamp <= NOW() AND 

如何获得未来的时间戳?

如果没有这一行,那么查询将如下所示:

SELECT  p.title, p.timestamp
FROM  posts_relationship pr INNER JOIN
      posts p
      ON p.id = pr.post_id
WHERE p.lang = 'it' AND
      pr.subcategory_id = 21
ORDER BY p.timestamp DESC;

使用此查询,posts(lang, timestamp, id)上的索引可能会阻止文件排序。以下版本的查询可能会更加确保这一点:

SELECT p.title, p.timestamp
FROM  posts p
WHERE p.lang = 'it' AND
      exists (select 1
              from posts_relationship pr
              where p.id = pr.post_id and pr.subcategory_id = 21
             )
ORDER BY p.timestamp DESC;

我不认为此查询将使用具有以下两个索引的文件排序:

posts(lang, id, timestamp)
posts_relationship(post_id, subcategory_id)

(顺便说一下,你可以保持时间戳的条件,我只是不明白为什么有必要。)