我有一个有关类别(价格,视图,设施,位置)的露营地的评论表。 以下查询用于按平均四个类别显示前20个评论。
SELECT
ROUND(((R.price + R.location + R.facilities + R.view) / 4), 2) AS avg,
R.poi_id,
poi.Name
FROM
`Reviews` AS `R`
LEFT JOIN `poi` ON `R`.`poi_id` = `poi`.`ID`
ORDER BY avg DESC
LIMIT 20
但是我已经意识到查询不适合同一个露营地有多个评论的情况。
那么有一个查询会返回最高的20个评级露营地(poi),其中包含该poiID的平均价格,视图,设施,位置/评论数量?
答案 0 :(得分:0)
平均功能当然是累积的,但你可以通过SUM
评论分数和COUNT
他们的数字来实现它:
SELECT
ROUND(((R.price + R.location + R.facilities + R.view) / 4 * cnt), 2) AS avg,
R.poi_id,
poi.Name
FROM
(SELECT SUM(price) AS price,
SUM(location) AS location,
SUM(facilities) AS facilities,
SUM(view) AS view,
COUNT(*) AS cnt,
poi_id
FROM Review
GROUP BY poi_id) AS `R`
LEFT JOIN `poi` ON `R`.`poi_id` = `poi`.`ID`
ORDER BY avg DESC
LIMIT 20