mysql - 我们如何得到两个表的值之和?

时间:2018-03-17 17:17:31

标签: mysql sql join

我有两张桌子

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

我们如何获得a.amount的总和(b_id = 20 AND b_id = 21)和a.status = 1?

答案应该是9000。

4 个答案:

答案 0 :(得分:2)

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

总计:9000

如果您可以添加相同数量的多次,我想这应该可以在没有连接的情况下工作:

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

答案 1 :(得分:0)

您可以使用子查询获得答案:

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));

无需将数据分组,因为我们需要所选金额的全局总和。

答案 2 :(得分:0)

试试这个:

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

答案 3 :(得分:0)

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) ;