我有两张桌子,用户:
以及用户的锻炼成绩,
paperId
显示锻炼ID,firstTry
显示是否是第一次尝试(值为0)或不是(其他值):
对于给定的教室(例如classrootm=1),我想用classroom=1
查询每个人的
max练习成绩,即使用户没有完成练习(就像那个叫欧阳锋的人)。
我的查询顺序是:
select u.*, s.* from users u
left join
(
select s.*
from (
select uid, max(score) as score, max(firstTry) as times
from scores
where paperId = 25
group by uid
) t, scores s
where
s.paperId = 25
AND s.uid = t.uid AND s.score = t.score AND s.firstTry = t.times
) s
on s.uid = u.uid
where classroom = 1
ORDER BY s.score DESC, s.id ASC
还能更简单一点吗?或者如何编写
mysql
序列以使查询工作更高效?看来我的查询连接表三次了😂
代码和演示在这里:http://sqlfiddle.com/#!9/a415566/8
如果您想将
firstTry
的值与最佳得分行相关联,您可以使用 GROUP BY
这样做。分组将确保用户仅返回一行。这里子查询的目标只是使 ORDER BY
分数递减,以便最好的分数排在第一位,因为 GROUP BY
将保留找到的第一行。另外,如果两行得分相同,我会按 s1.firstTry DESC
排序,以便返回具有 firstTry = 1
的行。如果您希望在相同分数的情况下先尝试行,只需将其更改为s1.firstTry ASC
。
select u.*, s.* from users u
left join
(
select s1.*
from scores s1
where
s1.paperId = 25
ORDER BY s1.score DESC, s1.firstTry DESC
) s on s.uid = u.uid
where classroom = 1
GROUP BY u.uid
ORDER BY s.score DESC, s.id ASC
您可以尝试以下
select u.*,s.* from users as u
left join
(
select max(s.score) as maxScore,s.uid from users as u
join scores as s on u.uid=s.uid
where u.classroom=1
group by uid
)as s on u.uid=s.uid
where u.classroom=1