加入两个表并保存到third-sql中

时间:2013-11-13 07:55:27

标签: mysql join

我想加入两张桌子。

表A

+-------------------+--------+
| wordA(primarykey) | countA |
+-------------------+--------+
| abc               |     25 |
| abcd              |     29 |
| abcde             |     45 |
+-------------------+--------+

表B

+-------------------+--------+
| wordB(primarykey) | countB |
+-------------------+--------+
| ab                |     10 |
| abc               |     40 |
| abcde             |     90 |
| abcdef            |     55 |
+-------------------+--------+

期望的输出:

表C

+--------+--------+--------+
|  word  | countA | countB |
+--------+--------+--------+
| ab     |      0 |     10 |
| abc    |     25 |    40  |
| abcd   |     29 |      0 |
| abcde  |     45 |     90 |
| abcdef |      0 |     55 |
+--------+--------+--------+

我想在TableC中插入所需输出的值。请提供一些代码。我试过这个,但我得到的问题是我无法合并wordA和wordB。

3 个答案:

答案 0 :(得分: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 Fiddle Demo

这会给你:

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

答案 1 :(得分: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小提琴here

答案 2 :(得分:1)

试试这个

仅针对MYSQL进行编辑

SQL Fiddle DEMO

Insert into TableC(word , countA , countB)
Select IFNULL(TableA.wordA , TableB.wordB) as word ,
IFNULL(TableA.countA , 0) as countA , IFNULL(TableB.countB , 0) as countB 
from TableA LEFT join TableB on TableA.wordA = TableB.wordB
Union
Select IFNULL(TableA.wordA , TableB.wordB) as word ,
IFNULL(TableA.countA , 0) as countA , IFNULL(TableB.countB , 0)
from TableA RIGHT join TableB on TableA.wordA = TableB.wordB;