我有三个不同的表用于3种不同的活动。公共字段是user_id。
性能:
id | user_id | date | mark
1 | 123 | xx | 20
2 | 456 | xx | 10
3 | 789 | xx | 5
4 | 123 | xx | 10
5 | 456 | xx | 10
6 | 789 | xx | 5
内部活动:
id | user_id | date | mark
1 | 123 | xx | 20
2 | 456 | xx | 10
3 | 789 | xx | 5
4 | 123 | xx | 10
5 | 456 | xx | 10
6 | 789 | xx | 5
其他活动:
id | user_id | date | mark
1 | 123 | xx | 20
2 | 456 | xx | 10
3 | 789 | xx | 5
4 | 123 | xx | 10
5 | 456 | xx | 10
6 | 789 | xx | 5
如何获取所有3个表中的每个用户标记,并在DESC中对其进行排序。结果应该像
id | user_id | mark
1 | 123 | 90
2 | 456 | 60
3 | 789 | 30
提前致谢
答案 0 :(得分:2)
SELECT tmp.ID,tmp.USER_ID,tmp.SUM(mark)
FROM
(select * from Performance
union all
select * from Internal_Activities
union all
select * from Other_Activities
) as tmp
group by tmp.USER_ID
注意: - 为什么要保留3个具有相同模式的独立表,不能将其设为一个?
答案 1 :(得分:1)
试试这个:
SELECT p.id, p.user_id, SUM(p.mark) FROM Performance p
LEFT JOIN Internal Activities ia ON p.id=ia.id
LEFT JOIN Other Activities oa ON ia.id=oa.id
GROUP BY p.user_id;
答案 2 :(得分:0)
SELECT
p.id
,p.user_id
,@performance:=p.mark AS performance
,@other_activities:=oa.mark AS other_activities
,@internal_activities:=ia.mark AS internal_activities
,@total_mark:=@performance+@other_activities+@internal_activities AS total_mark
FROM
table1 p
LEFT JOIN table2 ia
USING(user_id)
LEFT JOIN table2 oa
USING(user_id)