简体   繁体   中英

MySQL JOIN + Subquery Query Optimization

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:

DESCRIBE语法的结果

And here are my indexes on posts :

帖子索引

And my indexes on remixes :

混音索引

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

最新描述

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

Try not to wrap your JOIN in a sub-select as this will create an unindexed temporary table to store the result of the subselect in, where it then joins on that unindexed table.

Instead, put created_at as an additional join condition when joining the remixes table:

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

It seems to me that

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

could be rewritten as

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

which should give you a better EXPLAIN plan and run faster.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM