Mysql
 sql >> Database >  >> RDS >> Mysql

Unisci due tabelle e salva in terzo sql

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

Demo di SQL Fiddle

Questo ti darà:

|   WORD | COUNTA | COUNTB |
|--------|--------|--------|
|     ab |      0 |     10 |
|    abc |     25 |     40 |
|   abcd |     29 |      0 |
|  abcde |     45 |     90 |
| abcdef |      0 |     55 |