I changed the received response data and request.
The data is now a sample of data from a 5-star rating system.
Now the function correctly uses the average values of all messages.
The difference is in calculating these means, instead of PHP, they are calculated in SQL for the purpose of the answer.
You can see this in action on SQL Fiddle: http://sqlfiddle.com/#!9/84d8b/2/2
Updated request
New fiddle: http://sqlfiddle.com/#!9/3cdfe/1/2
SET @avg_total_votes := (SELECT AVG(meta_value) FROM postmeta WHERE meta_key ='this_num_votes'); SET @avg_total_rating := (SELECT AVG(meta_value) FROM postmeta WHERE meta_key ='this_rating'); SELECT posts.ID, posts.title, getmeta_votes.meta_value AS votes, getmeta_rating.meta_value AS rating, ( ( (@avg_total_votes * @avg_total_rating) + (getmeta_votes.meta_value * getmeta_rating.meta_value) ) / ( @avg_total_votes + getmeta_votes.meta_value ) ) AS factor FROM posts LEFT JOIN postmeta AS getmeta_votes ON posts.ID = getmeta_votes.post_id AND getmeta_votes.meta_key = 'this_num_votes' LEFT JOIN postmeta AS getmeta_rating ON posts.ID = getmeta_rating.post_id AND getmeta_rating.meta_key = 'this_rating' WHERE NOT getmeta_votes.meta_value = 0 AND NOT getmeta_rating.meta_value = 0 ORDER BY factor DESC;
I found that building this query was much faster, the previous one worked for 2 hours with a 2000 second dataset (1,000,000+ wp_postmeta lines) until it was complete.
This is done in 0.04 s.
source share