[英]SUM a field from other table with Left Join on MySQL and PHP
I have four tables: Table_A, Table_B, Table_C, and Table_D. 我有四个表:Table_A,Table_B,Table_C和Table_D。
TABLE_A
id_a | Name
A1 | ASD
A2 | ZXC
TABLE_B
id_b | id_a
B1 | A1
B2 | A2
TABLE_C
id_c | id_b | Value
C1 | B1 | 1
C2 | B1 | 1
C3 | B2 | 1
C4 | B2 | 1
C5 | B2 | 1
TABLE_D
id_d | id_a | Bill
D1 | A1 | 5
D2 | A2 | 10
I want to get SUM(table_c.value) as tot1 AND SUM(table_d.bill) as tot2 for each table_a.id_a, like below: 我想为每个table_a.id_a获取SUM(table_c.value)作为tot1和SUM(table_d.bill)作为tot2,如下所示:
id_a | SUM_VALUE of table_c | SUM_BILL of table_d
A1 | 2 | 5
A2 | 3 | 10
I'm using this script: 我正在使用此脚本:
$sql=" SELECT *, SUM(table_c.value) as tot1, SUM(table_d.bill) as tot2
FROM table_a
LEFT JOIN table_b ON table_b.id_a=table_a.id_a
LEFT JOIN table_c ON table_c.id_b=table_b.id_b
GROUP BY id_a ";
But getting the wrong result: 但是得到错误的结果:
id_a | SUM_VALUE of table_c | SUM_BILL of table_d
A1 | 2 | 10
A2 | 3 | 30
Any ideas? 有任何想法吗?
First find the SUM_VALUE_of_table_c
then Left join
the result with TableD
to find the SUM_BILL_of_table_d
which will avoid summing up of duplicate values in TableD
. 首先找到SUM_VALUE_of_table_c
然后将结果与TableD
Left join
以找到SUM_BILL_of_table_d
,这将避免对SUM_BILL_of_table_d
中的重复值TableD
。 Try this. 尝试这个。
SELECT F.id_a,
F.SUM_VALUE_of_table_c,
Sum(d.Bill) AS SUM_BILL_of_table_d
FROM (SELECT a.id_a,
Sum(c.Value) AS SUM_VALUE_of_table_c
FROM table_a A
LEFT JOIN table_b B
ON B.id_a = A.id_a
LEFT JOIN table_c C
ON c.id_b = B.id_b
GROUP BY a.id_a) F
LEFT JOIN TABLE_D D
ON d.id_a = F.id_a
Group by F.id_a
You could perform the sum calculation before joining: 您可以在加入之前执行总和计算:
SELECT a.id_a, b.sum_b, c.sum_c
FROM table_a a
JOIN table_b b ON a.id_a = b.id_b
JOIN (SELECT id_b, SUM(value)
FROM table_c
GROUP BY id_a) c ON b.id_b = c.id_b
JOIN (SELECT id_a, SUM(value)
FROM table_d
GROUP BY id_a) c ON a.id_a = d.id_b
I get the solution :) 我得到了解决方案:)
SELECT *,
Sum(bill) AS sum_of_tableD
FROM table_d,
table_a
LEFT JOIN (SELECT *,
Sum(table_c.value) AS sum_of_tableC
FROM table_c,
table_b
WHERE table_c.id_b = table_b.id_b
GROUP BY id_b) x
ON x.id_a = USER.id_a
WHERE table_d.id_a = table_a.id_a
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.