Domanda

I fear this could get quite complicated quite quickly, but I'm wondering what the best method is of showing the latest 'activity' ordered by 'popularity' - which is measures in either 'likes' or 'views' (even perhaps both, if possible - counting likes as 2x views?).

So if I have a database full of posts with views and/or likes, I want to be able to show the top 5% most popular, posts within the last 24 hours.

I have 3 tables for this, one for posts and two for the likes and views (1 row = 1 like / view)

table 1 = "posts"

id | title | timestamp | etc.

table 2 = "posts_likes"

post_id | user_id

table 3 = "posts_views"

post_id | user_id

Using MySQL + PHP, what would be the best way of running this query to order my posts by their overall, calulated popularity?

Many thanks, Tim

È stato utile?

Soluzione

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,

Altri suggerimenti

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 the COUNT() of all posts in the past 24 hours.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top