我有这两张桌子:
table1
uid points
5 13
7 9
12 5
17 3
1 1
2 2
3 1
table2
uid points
9 21
13 17
15 11
17 7
12 6
2 2
1 3
22 1
我需要一个查询来返回前5位用户有分数
目标结果:
uid points
9 21
13 17
5 13
12 11
15 11
我尝试了什么:
select uid, count(points) c from table1 order by c limit 5
union all
select uid, count(points) c from table2 order by c limit 5
但我没有得到我想要的东西。
答案 0 :(得分:1)
SELECT al.uid as UID , SUM(al.points) AS total_points FROM (SELECT points, uid FROM table1
UNION ALL
SELECT points,uid FROM table2) al group by al.uid
答案 1 :(得分:0)
试试这个
select uid, (table1.points + table2.points) as c from table1
Left join table2 on table1.uid = table2.uid
order by (table1.points + table2.points) desc limit 5
答案 2 :(得分:0)
您可以尝试此查询
Select
t3.uid , SUM(t3.points) As points
From
(SELECT * from Table1 UNION ALL SELECT * from Table2) t3
GROUP by
t3.uid
Order by
SUM(t3.points) DESC
LIMIT 5
答案 3 :(得分:0)
试试这个:
SELECT Uid,SUM(Points)
FROM
(
SELECT Uid,Points FROM Table1
UNION ALL
SELECT Uid,Points FROM Table2
) as T
GROUP BY Uid
ORDER BY SUM(Points) DESC
LIMIT 5
答案 4 :(得分:-1)
如果您想要排名前5位,则需要使用订单并限制子查询:
select uid, sum(points) points from (
select uid, points from table1
union all
select uid, points from table2
) x
group by uid
order by sum(points) desc
limit 5