mysql - 基于多个id来汇总多个表中的列

时间:2012-11-07 14:58:23

标签: mysql sql database sum

我有一个mySQL数据库,有几个相同的表。每次id1id2在至少2个表中相等时,我需要加入所有表并总结视图和点击,或者如果没有则只显示行。

请参见下表结构:

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

我希望这是有道理的,有人可以帮助它。

谢谢!

1 个答案:

答案 0 :(得分: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