我有一个用于记录分数的用户记录表(并且只需要获得成员用户)。我需要在今年获得每个用户的前5个分数,平均分数并返回前10名用户。
注意:用户必须至少有5个条目。
SCORE TABLE:
user_id | score | date_submitted
1 99 2017-11-07 22:00:00
2 55 2017-10-33 11:33:35
1 12 2017-09-33 11:33:35
USER TABLE
id | is_member
1 1
2 1
3 0
这是我到目前为止所做的:
SELECT s.user_id,
(SELECT AVG(s.score) FROM score s2 WHERE s2.user_id = s.user_id ORDER BY score DESC LIMIT 5) gr
FROM score s, users u
WHERE u.id = s.user_id
AND u.is_member = 1
AND YEAR(s.date_submitted) = YEAR(CURDATE())
GROUP BY s.user_id
HAVING COUNT(*) >= 5
ORDER BY gr DESC LIMIT 10
返回:
1242 - 子查询返回超过1行
我理解它是子查询中的限制,我试图弄清楚如何获得该用户的前5条记录。
答案 0 :(得分:1)
您不需要子查询。我还建议使用join
语法:
SELECT s.user_id, AVG(s.score) gr
FROM score s
INNER JOIN users u
ON u.id = s.user_id
AND u.is_member = 1
WHERE YEAR(s.date_submitted) = YEAR(CURDATE())
GROUP BY s.user_id
HAVING COUNT(*) >= 5
ORDER BY gr DESC
LIMIT 10
答案 1 :(得分:0)
以下查询将计算当前年度每位用户的最高(最高)5分的平均成绩并显示前10名用户:
SELECT s.user_id, AVG(s.score) gr
FROM (select * from score s
where YEAR(date_submitted) = YEAR(CURDATE())
and
(select count(*)
from score
where user_id = s.user_id
and score>=s.score
)<=5
) s
INNER JOIN users u
ON u.id = s.user_id
AND u.is_member = 1
GROUP BY s.user_id
HAVING COUNT(*) >= 5
ORDER BY gr DESC
LIMIT 10;
希望它有所帮助。