sql >> Base de Datos >  >> RDS >> Mysql

Une dos tablas y guarda en el tercer 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

Demostración de SQL Fiddle

Esto le dará:

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