I'm not sure this is even possible, but I need a confirmation before doing it the "ugly" way :)
So, the "results" are posts inside a database which are stored like this:
this_rating
) and the number of votes (this_num_votes
). This data is stored in pairs, the table has 3 columns: post ID / key / value. It's basically the WordPress table structure.What I want is to pull out the highest rated posts, sorted based on this formula:
br = ( (avg_num_votes * avg_rating) + (this_num_votes * this_rating) ) / (avg_num_votes +
this_num_votes
)
which I stole form here.
avg_num_votes
and avg_rating
are known variables (they get updated on each vote), so they don't need to be calculated.
Can this be done with a mysql query? Or do I need to get all the posts and do the sorting with PHP?
Data Stack Exchange Link:
https://data.stackexchange.com/stackoverflow/s/2137/order-database-results-by-bayesian-rating
SELECT id,title,( AVG(this_num_votes) * AVG(this_rating) + this_num_votes * this_rating )
/ ( AVG(this_num_votes) + this_num_votes ) as br
FROM posts
LEFT JOIN (
SELECT DISTINCT post_id,
(SELECT meta_value FROM postmeta WHERE postmeta.post_id = pm.post_id AND meta_key ='this_num_votes') as this_num_votes,
(SELECT meta_value FROM postmeta WHERE postmeta.post_id = pm.post_id AND meta_key ='this_rating') as this_rating
FROM postmeta pm ) as newmeta ON posts.ID = newmeta.post_id
GROUP BY id,title,this_num_votes,this_rating
ORDER BY br DESC
here it's a start to go:
// Bayesian Rating Calc
$theItem = $_GET[’id’];
if($theItem) {
// all items votes and ratings
$result = mysql_query(”SELECT AVG(item),AVG(vote) FROM itemvotes WHERE vote>’0′ GROUP BY item”) or die(mysql_error());
$row = mysql_fetch_row($result);
$avg_num_votes = $row[0];
$avg_rating = $row[1];
// this item votes and ratings
$result = mysql_query(”SELECT COUNT(item),AVG(vote) FROM itemvotes WHERE item=’$theItem’ AND vote>’0′”) or die(mysql_error());
$row2 = mysql_fetch_row($result);
$this_num_votes = $row2[0];
$this_rating = $row2[1];
if(!$row OR !$row2)
$br = “_”;
else
$br = number_format( ((($avg_num_votes * $avg_rating) + ($this_num_votes * $this_rating))/($avg_num_votes + $this_num_votes)), 1, ‘.’ );
} // end of if item selected
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With