在mysql中加入表

时间:2015-11-25 18:40:49

标签: mysql

我正在开发一个商业评论系统。 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条款。我怎样才能得到我的首选解决方案。提前致谢

2 个答案:

答案 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加入reviewreview表格是否应该包含对business.id

的引用的列

SQLFiddle here

祝你好运。

修改

通过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;

the updated SQLFiddle can be found here