Mysql
 sql >> Base de données >  >> RDS >> Mysql

Joindre deux tables et enregistrer dans le troisième 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

Démo SQL Fiddle

Cela vous donnera :

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