这是我的数据库:
此查询选择所有补充:
SELECT a.id, a.name, a.image, a.url_segment, COUNT(b.id) AS reviews_count, ROUND(AVG(b.rating), 2) AS reviews_rating, (((SELECT COUNT(*) FROM reviews) * (SELECT AVG(rating) FROM reviews)) + (COUNT(b.id) * AVG(b.rating))) / ((SELECT COUNT(*) FROM reviews) + COUNT(b.id)) AS bayesian_rating
FROM (`supplements` AS a)
LEFT JOIN `reviews` AS b ON `b`.`supplements_id` = `a`.`id`
GROUP BY `a`.`id`
ORDER BY `bayesian_rating` DESC
这是所有补充来自一个子类别(在这种情况下,id = 1):
SELECT a.id, a.name, a.image, a.url_segment, COUNT(b.id) AS reviews_count, ROUND(AVG(b.rating), 2) AS reviews_rating, (SELECT text FROM reviews WHERE supplements_id = a.id ORDER BY id DESC LIMIT 1) AS reviews_latest_text, (((SELECT COUNT(*) FROM reviews LEFT JOIN supplements ON (supplements.id = reviews.supplements_id AND supplements.subcategories_id = 1)) * (SELECT AVG(rating) FROM reviews LEFT JOIN supplements ON (supplements.id = reviews.supplements_id AND supplements.subcategories_id = 1))) + (COUNT(b.id) * AVG(b.rating))) / ((SELECT COUNT(*) FROM reviews LEFT JOIN supplements ON (supplements.id = reviews.supplements_id AND supplements.subcategories_id = 1)) + COUNT(b.id)) AS bayesian_rating
FROM (`supplements` AS a)
LEFT JOIN `reviews` AS b ON `b`.`supplements_id` = `a`.`id`
WHERE `a`.`subcategories_id` = '1'
GROUP BY `a`.`id`
ORDER BY `bayesian_rating` DESC
相同补充的贝叶斯评级在每个查询中应该是不同的,但两者都返回相同。
这是我在第一个查询中计算贝叶斯评级的部分:
(((SELECT COUNT(*) FROM reviews) * (SELECT AVG(rating) FROM reviews)) + (COUNT(b.id) * AVG(b.rating))) / ((SELECT COUNT(*) FROM reviews) + COUNT(b.id)) AS bayesian_rating
关于第二个:
(((SELECT COUNT(*) FROM reviews LEFT JOIN supplements ON (supplements.id = reviews.supplements_id AND supplements.subcategories_id = 1)) * (SELECT AVG(rating) FROM reviews LEFT JOIN supplements ON (supplements.id = reviews.supplements_id AND supplements.subcategories_id = 1))) + (COUNT(b.id) * AVG(b.rating))) / ((SELECT COUNT(*) FROM reviews LEFT JOIN supplements ON (supplements.id = reviews.supplements_id AND supplements.subcategories_id = 1)) + COUNT(b.id)) AS bayesian_rating
由于某种原因,加入对结果没有任何影响。
答案 0 :(得分:1)
由于评论是补充剂的孩子,加入补充剂不会返回任何不同的评论。
我认为期望两个查询返回相同的内容。
此外,通过AVG
的数学定义,术语
(SELECT COUNT(*) FROM reviews) * (SELECT AVG(rating) FROM reviews)
与
相同(SELECT SUM(rating) FROM reviews)
因此您可以简化(并加快)您的查询,但在此代替。