MySQL平均加入表

时间:2013-07-26 20:12:22

标签: mysql sql

我有两张桌子:

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

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


对不起,这是我的错。我从原始表中得到的数据错了。 真的很抱歉误导你:(

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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