MySQL Rating With Weight

夙愿已清 提交于 2019-12-06 11:28:21

A first step is to calculate avg_num_votes and avg_rating:

SELECT
  SUM(totalVotes)/COUNT(*) AS avg_num_votes,
  SUM(avgVote)/COUNT(*) AS avg_rating
FROM voting;

If you can live with a small error, it might be good enough to calculate that once in a while.

Now using your formula and the values above, you can run the weighing query. As a small optimization I precalculate avg_num_votes * avg_rating and call it avg_summand

SELECT
  voting.*, -- or whatever fields you need
  ($avg_summand+totalVotes*avgVote)/($avg_num_votes+totalVotes) AS bayesian
FROM voting
ORDER BY  bayesian DESC
LIMIT 1;

Edit

You could run this as a join:

SELECT
  voting.*, -- or whatever fields you need
  (avg_num_votes*avg_rating+totalVotes*avgVote)/(avg_num_votes+totalVotes) AS bayesian
FROM voting,
(
  SELECT
    SUM(totalVotes)/COUNT(*) AS avg_num_votes,
    SUM(avgVote)/COUNT(*) AS avg_rating
  FROM voting AS iv
) AS avg
ORDER BY  bayesian DESC
LIMIT 1;

But this will calculate sum and average on every single query - call it a performance bomb.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!