简体   繁体   English

如何获取两个表上的值的总和?

[英]mysql - How do we get the sum of the values on two tables?

I have two tables 我有两张桌子

table: a
---------------------
id    amount  status
---------------------
4031  3000    1
4032  4000    1
4033  5000    1
4034  6000    1
4035  7000    1
4036  8000    0
table: s
--------------
id a_id  b_id 
--------------
1  4031  20
2  4031  21
3  4032  23
4  4032  24
5  4033  25
6  4033  26
7  4034  21
8  4034  20
9  4035  25
10 4035  29
11 4036  21
12 4036  20

How do we get the sum of the a.amount where have ( b_id = 20 AND b_id = 21) AND a.status = 1? 我们如何获得a.amount的总和,其中有(b_id = 20 AND b_id = 21)和a.status = 1?

The answer should be 9000. 答案应该是9000。

SELECT SUM(amount) FROM (
JOIN s ON a.id = s.id
WHERE STATUS =1
AND (b_id = 20 OR b_id = 21) GROUP BY a.id
) AS amounts

total : 9000 合计:9000

In the case you can add several times the same amount, I guess this should work without join: 如果您可以添加相同数量的数倍,我想这应该在不加入的情况下起作用:

SELECT SUM(amount) AS total 
FROM `a`, `s` 
WHERE a_id = a.id AND (b_id = 20 OR b_id = 21) AND status = 1

total : 18000 合计:18000

You can get the answer using a subquery: 您可以使用子查询获得答案:

SELECT SUM(a.amount)
FROM a
WHERE a.status=1 AND
      EXISTS (SELECT 1
              FROM s
              WHERE s.a_id=a.id AND s.b_id in (20,21));

There is no need to group the data as we want the global sum of the amounts selected. 不需要对数据进行分组,因为我们希望选择的金额为全球总和。

Try this: 尝试这个:

select sum(a.amount)
from a 
join b on a.id = b.a_id 
where b.b_id IN ( 20, 21 ) and a.status = 1
SELECT SUM(a.amount)
FROM a
WHERE a.status=1 AND
      EXISTS (SELECT 1
              FROM s
              WHERE s.a_id=a.id AND s.b_id=20) AND 
              EXISTS (SELECT 1
              FROM s
              WHERE s.a_id=a.id AND s.b_id=21) ;

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

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