2

2 つのテーブルを結合したい。

表A

+--------------------+--------+
| | wordA(主キー) | カウント A |
+--------------------+--------+
| | abc | 25 |
| | abcd | 29 |
| | アブデ | 45 |
+--------------------+--------+

表B

+--------------------+--------+
| | wordB(主キー) | countB |
+--------------------+--------+
| | アブ | 10 |
| | abc | 40 |
| | アブデ | 90 |
| | abcdef | 55 |
+--------------------+--------+

望ましい出力:

表C

+--------+--------+--------+
| | 単語 | カウント A | countB |
+--------+--------+--------+
| | アブ | 0 | 10 |
| | abc | 25 | 40 |
| | abcd | 29 | 0 |
| | アブデ | 45 | 90 |
| | abcdef | 0 | 55 |
+--------+--------+--------+

目的の出力の値を TableC に挿入したいと考えています。いくつかのコードを提供してください。私はこれを試しましたが、私が得ている問題は、wordA と wordB をマージできないことです。

4

3 に答える 3

4
INSERT INTO TableC
SELECT
  t.word,
  SUM(COALESCE(a.countA, 0)) AS CountA,
  SUM(COALESCE(b.countB, 0)) AS countB
FROM
(
   SELECT wordA AS word FROM tableA
   UNION
   SELECT wordB FROM tableB
) AS t
LEFT JOIN tableA AS a on t.word = a.wordA
LEFT JOIN tableB AS b on t.word = b.wordb
GROUP BY t.word

SQL フィドルのデモ

これにより、次のことが得られます。

|   WORD | COUNTA | COUNTB |
|--------|--------|--------|
|     ab |      0 |     10 |
|    abc |     25 |     40 |
|   abcd |     29 |      0 |
|  abcde |     45 |     90 |
| abcdef |      0 |     55 |
于 2013-11-13T08:01:40.000 に答える
2
Insert into TableC
select wordA as word, countA, 0 as countB from TableA 
where wordA not in (select wordB from tableB)
union
select wordB as word, 0 as countA, countB from TableB
where wordB not in (select wordA from tableA)
union
select wordA as word, countA, countB 
from TableA join TableB on wordA=wordB
order by word asc 

ここでSQL フィドル

于 2013-11-13T08:09:59.307 に答える