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

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 に答える