简体   繁体   English

来自不同 MySQL 表中不同字段的总和

[英]Sum from different fields in different MySQL tables

I have these 2 tables:我有这两张表:

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

I need a query to return top 5 users have points我需要一个查询来返回前 5 位用户的积分

Target result:目标结果:

uid   points
9     21
13    17
5     13
12    11
15    11 

What I tried:我试过的:

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

But I did not get what I want.但我没有得到我想要的。

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

Try This试试这个

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

You can try this query你可以试试这个查询

  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

demo at http://sqlfiddle.com/#!2/5605d/23演示在http://sqlfiddle.com/#!2/5605d/23

Try this:试试这个:

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

SQLFiddle demo SQLFiddle 演示

If you want the top 5 overall, you need to use an order by and limit over a subquery:如果您想要总体前 5 名,则需要使用 order by 和 limit 子查询:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM