0

I'm trying to fetch 100 posts and order them by the number of times they've been "remixed" in the last week. Here is my query thus far:

SELECT COUNT(remixes.post_id) AS count, posts.title
FROM posts 
LEFT JOIN (
    SELECT * FROM remixes WHERE created_at >= 1343053513
) AS remixes ON posts.id = remixes.post_id
GROUP BY posts.id 
ORDER BY count DESC, posts.created_at DESC
LIMIT 100

This produces the correct result; however, after running DESCRIBE I get this:

Result of the DESCRIBE syntax

And here are my indexes on posts:

Posts Indexes

And my indexes on remixes:

Remixes Indexes

And here are my questions:

  1. Can you explain what the terms used in the extra column are really trying to tell me?
  2. Could you provide tips on how I can optimize this query so that it'll scale better.

Thanks in advance!

Update

Per Zane's solution, I've updated my query to:

SELECT COUNT(remixes.post_id) AS count, posts.title
FROM posts 
LEFT JOIN remixes ON posts.id = remixes.post_id AND remixes.created_at >= 1343053513
GROUP BY posts.id 
ORDER BY count DESC, posts.created_at DESC
LIMIT 100

And here's the latest DESCRIBE

LATEST DESCRIBE

I'm still worried about the filesort part. Any ideas?

4

2 回答 2

1

尽量不要将您包装JOIN在子选择中,因为这将创建一个未索引的临时表来存储子选择的结果,然后它会在该未索引表上连接。

相反,created_at在加入 remixes 表时作为附加的加入条件:

SELECT 
    a.title, COUNT(b.post_id) AS remixcnt
FROM 
    posts a
LEFT JOIN 
    remixes b ON a.id = b.post_id AND b.created_at >= 1343053513
GROUP BY 
    a.id, a.title
ORDER BY 
    remixcnt DESC, a.created_at DESC
LIMIT 100
于 2012-07-22T23:13:25.690 回答
0

在我看来,这

SELECT COUNT(remixes.post_id) AS count, posts.title
FROM posts 
LEFT JOIN (
    SELECT * FROM remixes WHERE created_at >= 1343053513
) AS remixes ON posts.id = remixes.post_id
GROUP BY posts.id 
ORDER BY count DESC, posts.created_at DESC
LIMIT 100

可以改写为

SELECT COUNT(r.post_id) AS count, posts.title
FROM posts 
LEFT JOIN remixes r ON posts.id = r.post_id
WHERE r.created_at >= 1343053513
GROUP BY posts.id 
ORDER BY count DESC, posts.created_at DESC
LIMIT 100

这应该会给你一个更好的EXPLAIN计划并且跑得更快。

于 2012-07-22T22:50:17.577 回答