Et første skridt er at beregne avg_num_votes
og avg_rating
:
SELECT
SUM(totalVotes)/COUNT(*) AS avg_num_votes,
SUM(avgVote)/COUNT(*) AS avg_rating
FROM voting;
Hvis du kan leve med en lille fejl, kan det være godt nok at regne det ud en gang imellem.
Nu ved at bruge din formel og værdierne ovenfor, kan du køre vejningsforespørgslen. Som en lille optimering forudberegner jeg avg_num_votes * avg_rating
og kald det 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;
Rediger
Du kan køre dette som en joinforbindelse:
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;
Men dette vil beregne sum og gennemsnit for hver enkelt forespørgsel - kald det en præstationsbombe.