2012-11-07 38 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,所以这太棒了!谢谢你的回答,它也帮助了我! –