3

我有一个带有几个相同表的 mySQL 数据库。我需要加入所有表并在至少 2 个表中每次id1和相等时总结视图和点击,或者如果不是则简单地显示该行。id2

请看下表结构:

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

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

谢谢 !

4

1 回答 1

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
于 2012-11-07T15:00:09.740 回答