我正在开发一个商业评论系统。
business
表是 -
id category
1 1
2 1
3 1
4 2
review
表是 -
id bid reviewer_point
1 1 4
2 1 3
3 2 4
4 2 5
我需要返回10
过滤后评分最高的business ID
category
个(基于评分点平均值)业务。
到目前为止,我可以找到每项业务的平均评分。
SELECT business.category, bid,
COUNT(*) AS review_count, AVG(reviewer_point) AS average_points
FROM reviews
GROUP BY bid
ORDER BY average_points DESC WHERE category = 1 LIMIT 10;
我无法使用WHERE
条款。我怎样才能得到我的首选解决方案。提前致谢
答案 0 :(得分:2)
mysql单个查询中的顺序是:
1st SELECT;
2nd FROM;
3rd WHERE;
4th GROUP BY;
5th HAVING;
6th ORDER BY;
7th LIMIT.
尝试将每个都放在一个断行线上。
答案 1 :(得分:1)
WHERE子句必须在GROUP BY
之前SELECT business.category, bid,
COUNT(*) AS review_count, AVG(reviewer_point) AS average_points
FROM review
WHERE category = 1
GROUP BY bid
ORDER BY average_points DESC
LIMIT 10;
但是,由于business
表尚未加入此查询,因此仍然无效。我会包含此内容,但没有明显的方法可以将business
加入review
。 review
表格是否应该包含对business.id
?
祝你好运。
通过OP在评论(下面)中提供的信息,修订后的查询变为
SELECT b.category, r.bid,
COUNT(*) AS review_count, AVG(reviewer_point) AS average_points
FROM review r
INNER JOIN business b
ON b.id = r.bid
WHERE b.category = 1
GROUP BY r.bid, b.category
ORDER BY average_points DESC
LIMIT 10;