2012-11-07 47 views
3

我有一個mySQL數據庫,有幾個相同的表。我需要加入所有表格,並且每次至少在2個表格中對id1id2進行相等處理,然後總結觀點和點擊次數,如果不是,則只需顯示該行。mysql - 基於多個id的多個表的總和列

請參考下面的表格結構:

Table1: 
id..id2...views...hits 
1...102...55......12 
2...103...12......22 

Table2: 
id..id2...views...hits 
1...123...512......13 
2...103...123......43 

Table3: 
id..id2...views...hits 
1...102...232......43 
2...103...100......70 

最終的結果應該是如下表:

id...id2...views...hits 
1....102...287....65 <-- This one is the result of adding 1st row of table1 and 2nd row of table 2 
1....123...512....13 <-- This is the 1st row of table2 as there's no other id2 = 123 
2....103...235....135 <-- This is the sum of 2nd row in table1 + 2nd row in table2 + 2nd row in table3 

我希望這是有道理的,有人可以用它幫助。

謝謝!

回答

3

與工會把所有三個表的行在一起,然後組和像往常一樣:

SELECT id, id2, SUM(views), SUM(hits) 
FROM 
(
    SELECT id, id2, views, hits 
    FROM Table1 
    UNION ALL 
    SELECT id, id2, views, hits 
    FROM Table2 
    UNION ALL 
    SELECT id, id2, views, hits 
    FROM Table3 
) x 
GROUP BY id, id2 
+0

哈啊,我是個白癡!我認爲這是不行的,因爲2 ID,但你是對的。非常感謝 ! – user1806446

+0

這個語法也適用於SQLite,所以這太棒了!謝謝你的回答,它也幫助了我! –