[英]Sum of field from 5 table on MySQL
I have 5 tables on MySQL, following: 我在MySQL上有5个表,如下:
Table A
ID-A | NAME
A1 | Name A
A2 | Name b
Table B
ID-B | ID-A
B1 | A1
B2 | A2
Table C
ID-C | ID-B | Value-C
C1 | B1 | 1
C2 | B2 | 1
C3 | B1 | 1
Table D
ID-D | ID-A | Value-D
D1 | A1 | 1000
D2 | A1 | 500
D3 | A1 | 1000
D4 | A2 | 1000
D5 | A2 | 500
Table E
ID-E | ID-A | Value-E
E1 | A1 | 2000
E2 | A1 | 1500
E3 | A2 | 500
E4 | A2 | 500
E5 | A2 | 1000
So, I want sum of value, following: 所以,我想要的价值总和如下:
1. SUM(Value-C)
of Table C AS tot_C
for each ID-A
of Table A. 1.表A的每个
ID-A
的表C AS tot_C
SUM(Value-C)
。
2. SUM(Value-D)
of Table D AS tot_D
for each ID-A
of Table A. 2.表D的
SUM(Value-D)
为表ID-A
的每个ID-A
的tot_D
。
3. SUM(Value-E)
of Table E AS tot_E
for each ID-A
of Table A. 3.对于表A的每个
ID-A
,表SUM(Value-E)
的表SUM(Value-E)
为tot_E
。
4. tot_C+tot_D+tot_E
AS tot_ALL
for each ID-A
of Table A. 4.表A的每个
ID-A
的tot_C+tot_D+tot_E
AS tot_ALL
。
I hope you can help me. 我希望你能帮助我。
Thank you, Dear! 谢谢亲爱的!
select tb.id_A id_A, sum(valueC) tot_C
from fiveTablesSum_C tc
join fiveTablesSum_B tb on tc.id_B = tb.id_B
group by id_A;
+------+-------+
| id_A | tot_C |
+------+-------+
| A1 | 2 |
| A2 | 1 |
+------+-------+
select id_A id_A, sum(valueD) tot_D from fiveTablesSum_D group by id_A;
+------+-------+
| id_A | tot_D |
+------+-------+
| A1 | 2500 |
| A2 | 1500 |
+------+-------+
select id_A id_A, sum(valueE) tot_E from fiveTablesSum_E group by id_A;
+------+-------+
| id_A | tot_E |
+------+-------+
| A1 | 3500 |
| A2 | 2000 |
+------+-------+
select
t1.id_A,
t2.tot_C, t3.tot_D, t4.tot_E,
t2.tot_C + t3.tot_D + t4.tot_E tot_ALL
from fiveTablesSum_A t1
left join (
select tb.id_A id_A, sum(valueC) tot_C
from fiveTablesSum_C tc
join fiveTablesSum_B tb on tc.id_B = tb.id_B
group by id_A
) t2 on t1.id_A = t2.id_A
left join (
select id_A id_A, sum(valueD) tot_D from fiveTablesSum_D group by id_A
) t3 on t1.id_A = t3.id_A
left join (
select id_A id_A, sum(valueE) tot_E from fiveTablesSum_E group by id_A
) t4 on t1.id_A = t4.id_A
;
+------+-------+-------+-------+---------+
| id_A | tot_C | tot_D | tot_E | tot_ALL |
+------+-------+-------+-------+---------+
| A1 | 2 | 2500 | 3500 | 6002 |
| A2 | 1 | 1500 | 2000 | 3501 |
+------+-------+-------+-------+---------+
For your first query, try like below 对于您的第一个查询,请尝试如下
SELECT
SUM(TableC.Value-C) as tot_C,TableC.ID-C
FROM
TableC
JOIN
TableB ON TableB.ID-B = TableC.ID-B
JOIN
TableA ON TableA.ID-A = TableB.ID-A;
Similarly you can try other other queries as well , You should look for how to use JOINS 同样,您也可以尝试其他查询,您应该寻找如何使用JOINS的方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.