2016-05-17 74 views
2

我想要左連接多個表與兩個總和列都加入中步表。左連接表與總和 - 導致問題

的表格看起來像:

表1

ID Value1 
1 3 
2 2 
3 3 

表2

ID Value1 
1 5 
2 2 
3 2 
4 1 

Jointable

ID 
1 
2 
3 
4 
5 
6 

我試圖輸出:

Table1Value1SUM Table2Value1Sum 
8 | 10 

隨着SQL:

SELECT SUM(Table1.Value1) Table1Value1SUM,SUM(Table2.Value1) Table2Value1Sum From Table1 
Left Join JoinTable 
On JoinTable.ID = Table1.ID 
Left Join Table2 
On Table2.ID = Table1.ID 

我得到這些結果:

Table1Value1SUM Table2Value1Sum 
8 | 9 
+0

它在答覆中提到,但你的連接表有絕對無關,與你的問題。此外,連接表至少有兩列:一個表中的PK - 和另一個表中的PK(因此術語:「連接表」)。 –

回答

3

jointable必須是在left join版與另外兩張桌子。

SELECT SUM(Table1.Value1) Table1Value1SUM,SUM(Table2.Value1) Table2Value1Sum 
From JoinTable 
Left Join Table1 On JoinTable.ID = Table1.ID 
Left Join Table2 On JoinTable.ID = Table2.ID 
1

Left JoinTable2JoinTable代替Table1

SELECT SUM(Table1.Value1) Table1Value1SUM,SUM(Table2.Value1) Table2Value1Sum From Table1 
Left Join JoinTable 
On JoinTable.ID = Table1.ID 
Left Join Table2 
On JoinTable.ID = Table2.ID 
0

有什麼用jointable這來?你想Table 1和表2的總和,因此:

select 
    (select sum(value1) from table1) as table1sum, 
    (select sum(value1) from table2) as table2sum 

select t1.table1sum, t2.table2sum 
from 
    (select sum(value1) as table1sum from table1) t1 
cross join 
    (select sum(value1) as table2sum from table2) t2;