2

我想加入两张桌子。

表A

+-------------------+--------+
| wordA(主键) | 计数 |
+-------------------+--------+
| 美国广播公司 | 25 |
| abcd | 29 |
| abcde | 45 |
+-------------------+--------+

表B

+-------------------+--------+
| wordB(主键) | 计数B |
+-------------------+--------+
| ab | 10 |
| 美国广播公司 | 40 |
| abcde | 90 |
| abcdef | 55 |
+-------------------+--------+

期望的输出:

表C

+--------+--------+--------+
| 词 | 计数 | 计数B |
+--------+--------+--------+
| ab | 0 | 10 |
| 美国广播公司 | 25 | 40 |
| abcd | 29 | 0 |
| abcde | 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 回答
1

试试这个

仅针对 MYSQL 编辑

SQL 小提琴演示

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;
于 2013-11-13T08:03:20.430 回答