我想出了另一个问题。我正在尝试设计一个MySql查询。
我有一个Users
表和Ratings
表,其中user_id
作为评级表中的外键。
现在我必须得到平均评分最高的用户
所以我做了:
SELECT blah blah FROM Users USR
INNER JOIN Ratings RTN on USR.id = RTN.user_id
order by avg(RTN.rating)
但是我觉得这是错误的,它也没有用。有没有办法让用户按照降序收到的平均收视率排序?
此致 Himanshu Sharma。
答案 0 :(得分:1)
如果要包含评分数据,可以使用计算平均评分的内联视图,然后加入该评级。
SELECT blah blah
FROM Users USR
INNER JOIN Ratings RTN
ON USR.id = RTN.user_id
INNER JOIN (SELECT avg(RTN.rating) Avg_rating
FROM Ratings RTN
GROUP BY
rtn.user_id) a_rtn
ON USR.id = A_RTN.user_id
ORDER BY avg(A_RTN.AVg_rating) DESC
如果您只想要用户数据而不需要标准的分组
SELECT USR.First_name, USR.Last_name, etc
FROM Users USR
INNER JOIN Ratings RTN
ON USR.id = RTN.user_id
GROUP BY
USR.First_name, USR.Last_name, etc
ORDER BY avg(A_RTN.AVg_rating) DESC
答案 1 :(得分:1)
你的查询实际上并不是非常错误(作为开头),我会这样写:
SELECT USR.id, AVG(RTN.rating) AS avg_rating
FROM Users USR
INNER JOIN Ratings RTN ON USR.id = RTN.user_id
GROUP BY USR.id
ORDER BY avg_rating DESC
LIMIT 1
答案 2 :(得分:1)
select blah, blah
from users usr
join (
select rtn.user_id, avg(rtn.rating) as avg_rating
from users usr
join ratings rtn on usr.id = rtn.user_id
group by rtn.user_id
) t on t.user_id = usr.id
order by avg_rating desc