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 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

由于某种原因,连接对结果没有任何影响。

4

1 回答 1

1

由于评论是补充品的孩子,加入补充品不会返回任何不同的评论。

我认为这两个查询返回相同的结果。


此外,根据 的数学定义AVG,术语

(SELECT COUNT(*) FROM reviews) * (SELECT AVG(rating) FROM reviews)

等同于

(SELECT SUM(rating) FROM reviews)

因此您可以简化(并加快)您的查询,但将其替换为。

于 2012-11-24T17:31:21.263 回答