0

我有 3 张桌子:

user(id, name, id_school)
school(id, name)
result(id_user, stage1, stage2)

现在我想获得学校排名 - 是 2 列的总和:所有用户的 stage1 和 stage2。

4

3 回答 3

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

我真的希望你有索引。

于 2013-02-15T13:12:41.183 回答
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

希望它有帮助,祝你好运:)

于 2013-02-15T13:07:40.253 回答
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 
于 2013-02-15T13:04:22.533 回答