假設我有3個表我想加入兩列3個表和彙總記錄從這些表2,同時避免記錄重複
答:
---------------
id | name
---------------
1 | A
---------------
2 | B
---------------
B:
-----------------------
id | val | A_id
-----------------------
1 | 10 | 1
-----------------------
2 | 20 | 2
-----------------------
3 | 30 | 2
-----------------------
C:
-----------------------
id | val | B_id
-----------------------
1 | 40 | 2
-----------------------
2 | 50 | 2
-----------------------
3 | 60 | 2
-----------------------
How我得到這樣的結果:
----------------------------
A_name | B_val | C_val
----------------------------
A | 10 | 0
----------------------------
B | 50 | 150
----------------------------
我試着這樣做:
SELECT A.name, SUM(COALESCE(B.val,0)), SUM(COALESCE(C.val,0))
FROM A
LEFT JOIN B ON A.id = B.A_id
LEFT JOIN C ON B.id = C.B_id
GROUP BY A
但它返回此相反:
----------------------------
A_name | B_val | C_val
----------------------------
A | 10 | 0
----------------------------
B | 90 | 150
----------------------------
我想這是因爲C有3所記載,與B有關,所以B的第二個記錄乘以3。什麼是獲得我想要的結果的最佳方式?