How would I implement a ranking algorithm in my website to sort database data?

佐手、 提交于 2019-12-04 10:41:53

You can use the data you need in the ORDER BY clause.

SELECT p.id, p.title, p.time_submitted, SUM(v.score) as num_votes 
  FROM posts p, votes v
 WHERE v.postid = p.id
GROUP BY p.id
ORDER BY 
   (SUM(v.score) - 1) / POW(TIMESTAMPDIFF(HOUR,p.time_submitted,NOW()) + INTERVAL 2 HOUR, 1.8) DESC
LIMIT 100

In your case, the number of votes would be returned by:

SELECT count(*) FROM votes WHERE postid=<THE POST'S ID>;

If you want to consider score, you could include that in the query but the formula you provided is not equipped to handle it.

The item hour age is simply the current time subtracted from the time submitted:

SELECT HOUR(TIMEDIFF(NOW(), time_submitted)) FROM posts WHERE id=<THE POST'S ID>;

This can also be done entirely in SQL:

SELECT id FROM posts ORDER BY (((SELECT count(*) FROM votes WHERE postid=posts.id) - 1) / MOD(HOUR(TIMEDIFF(NOW(), time_submitted) + INTERVAL 2 HOURS), <GRAVITY>)) LIMIT 10;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!