I have posts
, votes
, and comments
tables. Each post can have N yes votes , N no votes and N comments. I am trying to get a set of posts sorted by number of yes votes.
I have a query that does exactly this, but is running far too slowly. On a data set of 1500 posts and 15K votes, it s take .48 seconds on my dev machine. How can I optimize this?
select
p.*,
v.yes,
x.no
from
posts p
left join (select post_id, vote_type_id, count(1) as yes from votes where (vote_type_id = 1) group by post_id) v on v.post_id = p.id
left join (select post_id, vote_type_id, count(1) as no from votes where (vote_type_id = 2) group by post_id) x on x.post_id = p.id
left join (select post_id, count(1) as comment_count from comments group by post_id) p on p.confession_id = p.id
order by
yes desc
limit
0, 10
EDIT:
Votes
andComments
both have apost_id
FK- Adding an index on
vote_type_id
andpost_id
in thevotes
table shaved .1sec off the query execution.