【问题标题】:mysql - sum columns from multiple tables based on multiple id'smysql - 基于多个 id 对来自多个表的列求和
【发布时间】:2012-11-07 14:58:22
【问题描述】:

我有一个带有几个相同表的 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

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

谢谢!

【问题讨论】:

    标签: mysql sql database sum


    【解决方案1】:

    将所有三个表的行用一个并集放在一起,然后像往常一样分组和求和:

    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
    

    【讨论】:

    • 啊啊啊我是个白痴!我认为这行不通,因为有 2 个 ID,但你是对的。非常感谢!
    • 这种语法也适用于 SQLite,太棒了!谢谢你的回答,对我也有帮助!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多