这个问题继续我之前的问题。
join 2 tables and save into third-sql
这一次,情况是这样的
TableA
+-------------------+--------+
| wordA(primarykey) | countA |
+-------------------+--------+
| pqr | 5 |
| abcd | 20 |
| pqrs | 45 |
+-------------------+--------+
TableB
+-------------------+--------+
| wordB(primarykey) | countB |
+-------------------+--------+
| pq | 10 |
| abc | 10 |
| pqrs | 10 |
| abcdef | 5 |
+-------------------+--------+
这次TableC已经有了这些元组。如果TableC中已存在任何单词,则其计数将增加TableA或TableB的值。如果没有,则将新单词添加到其中。这就像我们正在更新表并插入更新未完成。
TableC(before query)
+--------+--------+--------+
| word | countA | countB |
+--------+--------+--------+
| ab | 0 | 10 |
| abc | 25 | 40 |
| abcd | 29 | 0 |
| abcde | 45 | 90 |
| abcdef | 0 | 55 |
+--------+--------+--------+
Desired output:
TableC(after query)
+--------+--------+--------+
| word | countA | countB |
+--------+--------+--------+
| ab | 0 | 10 |
| abc | 25 | 50 |
| abcd | 49 | 0 |
| abcde | 45 | 90 |
| abcdef | 0 | 60 |
| pq | 0 | 10 |
| pqr | 5 | 0 |
| pqrs | 45 | 10 |
+--------+--------+--------+
答案 0 :(得分:3)
在MySQL中,如果使用ON DUPLICATE KEY语法TableC.Word
是PRIMARY KEY,则可以在一个查询中执行此操作:
INSERT INTO TableC(Word,CountA,CountB)
SELECT * FROM
(
SELECT Word,SUM(CountA) as Ca,SUM(CountB) as Cb
FROM
(
SELECT WordA as Word,CountA, 0 as CountB FROM TableA
UNION ALL
SELECT WordB as Word,0 as CountA, CountB FROM TableB
) T GROUP BY Word
) T1
ON DUPLICATE KEY
UPDATE CountA = CountA+T1.Ca,CountB = CountB+T1.Cb
答案 1 :(得分:0)
使用 ON DUPLICATE KEY UPDATE 试试这可能对您有所帮助。
INSERT INTO 'your previos query'
ON DUPLICATE KEY UPDATE
countA = coutnA +1