我有3张桌子:
user(id, name, id_school)
school(id, name)
result(id_user, stage1, stage2)
现在我想获得学校排名 - 是2列的总和:所有用户的stage1和stage2。
答案 0 :(得分:2)
似乎太简单了:
select s.name as school, sum(stage1)+sum(stage2) as rank
from result r
join user u on u.id=r.id_user
join school s on s.id=u.id_school
group by s.id
我真的希望你有索引。
答案 1 :(得分:0)
尝试此查询。这只是假设。请为测试提供一些数据
SELECT
s.id,
s.name AS SchoolName
(r.S1 + r.S2) AS Rank
FROM school as s
LEFT JOIN user as u ON u.id_school = s.id
LEFT JOIN (SELECT id_user , SUM(stage1) as S1 , SUM(stage2) FROM result GROUP BY id_user) as r ON r.id_user = u.id
GROUP BY s.id
ORDER BY Rank DESC
答案 2 :(得分:0)
我会做这样的事情:
SELECT school.name, SUM(result.result1 + result.result2)
FROM school LEFT JOIN user ON (user.id_school = school.id) LEFT JOIN result ON (result.id_user = user.id) GROUP BY school.id
希望它有所帮助,祝你好运:)。