php - MySQL find top x% across a given time period

Solution:
I will give you some pseudo sql just to show the idea I would use, you can add the missing bits and get it working. It assumes that the top 5% is based in the number of posts, but if it was based in the score of likes plus views, should be trivial to adjust.
SET @foo=0.05 * select count(*) from posts where (timestamp < today - 24 hours);
PREPARE STMT FROM 'SELECT posts,sum(likes) * 2 + sum(views) as POPULAR FROM (tables joined) ORDER BY popular LIMIT ?';
EXECUTE STMT USING @foo;
Regards,
Answer
Solution:
I can't test this, as I don't have a MySQL server accessible right now - but the below query should get you started:
SELECT p.id, p.title, ((COUNT(l.id) * 2) + COUNT(v.id)) AS popularity
FROM posts p
LEFT JOIN posts_likes l ON l.post_id = p.id
LEFT JOIN posts_views v ON v.post_id = p.id
WHERE p.timestamp > (UNIX_TIMESTAMP()-86400)
GROUP BY p.id
ORDER BY popularity DESC LIMIT :return_limit
When you run the query, you'll need to pass a parameter:return_limit
- Which should be 5% of theCOUNT()
of all posts in the past 24 hours.
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: php_network_getaddresses: getaddrinfo failed: temporary failure in name resolution
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.