假设我有3个表格,如下所示:
用户
oauth_uid | name
1 | John Claude
2 | Nick Jonas
3 | Justin Timberlake
测试
oauth_id | score
1 | 30
2 | 28
1 | 20
3 | 18
2 | 34
训练
oauth_id | score
2 | 3
1 | 8
1 | 2
2 | 18
我想按以下条件订购用户:
到目前为止,我已经能够满足前两个条件:
select test.oauth_id, max(test.score) as score, users.name
from users inner join
test
on test.oauth_id = users.oauth_uid
group by test.oauth_id
order by score desc
select sum(training.score) as tr_score
from training
group by training.oauth_id
order by tr_score desc
如何添加两者并按总分进行排序?
答案 0 :(得分:1)
使用子查询:
select u.*, max_score, sum_score,
(coalesce(max_score, 0) + coalesce(sum_score, 0)) as overall_score
from users u left join
(select oauth_id, max(score) as max_score
from test
group by oauth_id
) te
on te.oauth_id = u.oauth_id left join
(select oauth_id, sum(score) as sum_score
from test
group by oauth_id
) tr
on tr.oauth_id = u.oauth_id
order by overall_score desc;