0

我有两张桌子:

salon_ranks

+-----------+-----------+-----------+-----------+
| salon_id  |category_id|  user_id  |    rank   |
+-----------+-----------+-----------+-----------+
|        10 |         1 |       999 |       1   |
|        10 |         2 |       999 |       1   |
|        10 |         1 |       888 |       5   |
|        10 |         2 |       888 |       5   |
+-----------+-----------+-----------+-----------+

categories

+------+-----------+
|  id  |    name   |
+------+-----------+
|   1  |   prices  |
|   2  |   service |
+------+-----------+

我正在尝试有效地获得如下所示的东西:

+-----------+-----------+-----------+
| salon_id  |category_id| AVG(rank) |
+-----------+-----------+-----------+
|        10 |         1 |       3   |
|        10 |         2 |       3   |
+-----------+-----------+-----------+

对我来说最有意义的是这样的查询:

SELECT salon_id, category_id, AVG(rank)
FROM salon_ranks
INNER JOIN categories ON category_id = id
GROUP BY salon_id, category_id

但由于某种原因,我没有得到平均值,而是得到了这个:

+-----------+-----------+-----------+
| salon_id  |category_id| AVG(rank) |
+-----------+-----------+-----------+
|        10 |         1 |       1   |
|        10 |         2 |       5   |
+-----------+-----------+-----------+

知道为什么会发生吗?什么可能是正确的查询?


对不起,是我的错。我从原始表格中获取的数据错误。真的很抱歉误导你:(

4

2 回答 2

3

您的解决方案:

http://www.sqlfiddle.com/#!2/ee5c6/2

SELECT SR.salon_id, SR.category_id, AVG(SR.rank)
FROM salon_ranks SR
INNER JOIN categories C ON SR.category_id = C.id
GROUP BY SR.salon_id, SR.category_id
于 2013-07-26T20:19:37.547 回答
2

现在我们知道您的查询工作正常。但最好为表使用别名。对于您的情况,这不是必需的,但它使您的查询更具可读性和可扩展性。

SELECT SR.salon_id, SR.category_id, AVG(SR.rank)
FROM salon_ranks SR
INNER JOIN categories C ON SR.category_id = C.id
GROUP BY SR.salon_id, SR.category_id
于 2013-07-26T20:15:57.017 回答