Home » Php » php – How can make sort by votes "by date", "by year"..?

php – How can make sort by votes "by date", "by year"..?

Posted by: admin July 12, 2020 Leave a comment

Questions:

What I am trying to implement is similar to what we have on SO. I want to rank posts by upvotes in last day, last month etc. My schema makes up two tables,

post(id, post, posted_on..)
vote(post_id, vote_value, date)

I hope the schema is pretty self explanatory. The problem being, if I sort “by day” by making a inner join on posts and vote and having a where clause(‘votes.date >= DATE_SUB(CURDATE(), INTERVAL 1 DAY‘), it does work as intended but fails to show the other posts. I mean the posts which haven’t had vote in last day are completely ignored. What I want is that those posts be given low priority but do show up in the query.

While, I may think of using union operation but i was looking for another approach.

Update: Lets say, there are two posts, 1,2.

and votes table is like,

post_id       vote_value      date
1              1              2012-12-19
2              1              2012-12-10

If I query, as per my approach, then only the post – “1” will show up since I have put a date constraint but I want both to show up. Here is my query:

SELECT `id`, SUM(`votes`.`votes`) AS likes_t, `post`.* FROM `posts` JOIN `votes` ON (`id` = `votes`.`post_id`) WHERE `votes`.`date` >= DATE_SUB(CURDATE(), INTERVAL 2 DAY) 
How to&Answers:

If you want to show all posts, but only count the recent votes, this should do it:

SELECT `id`,
       SUM(IF(`votes`.`date` >= DATE_SUB(CURDATE(), INTERVAL 2 DAY, `votes`.`votes`, 0)) AS likes_t, 
       `post`.*
       FROM `posts` JOIN `votes` ON (`id` = `votes`.`post_id`)

Answer:

If I got it right:

SELECT *, IF(vote.date>=DATE_SUB(CURDATE(), INTERVAL 1 DAY), 1, 0) as rate FROM post INNER JOIN vote ON (post.id=vote.post_id) ORDER BY rate DESC;

+------+--------+---------+------+---------------------+------+
| id   | post   | post_id | vote | date                | rate |
+------+--------+---------+------+---------------------+------+
|    1 | first  |       1 |    1 | 2012-12-19 00:00:00 |    1 |
|    1 | first  |       1 |    1 | 2012-12-13 00:00:00 |    0 |
|    2 | second |       2 |    1 | 2012-12-10 00:00:00 |    0 |
+------+--------+---------+------+---------------------+------+