您將執行一個更新和一個刀片,先更新匹配的,然後插入缺少的。
這裏是一個完整的SQLite3腳本演示您的問題和結果:
CREATE TABLE Table1 (Word TEXT NOT NULL PRIMARY KEY, Score INTEGER NOT NULL);
CREATE TABLE Table2 (Word TEXT NOT NULL PRIMARY KEY, Score INTEGER NOT NULL);
INSERT INTO Table1 VALUES ('Abstract', 12), ('standard', 15), ('space', 30);
INSERT INTO Table2 VALUES ('Abstract', 2), ('standard', 2), ('aroma', 50);
UPDATE Table1
SET Score = Score + (SELECT SUM(Score) FROM Table2 WHERE Table1.Word = Table2.Word)
WHERE Word IN (SELECT Word FROM Table2);
INSERT INTO Table1
SELECT *
FROM Table2
WHERE Table2.Word NOT IN (SELECT Word FROM Table1);
SELECT * FROM Table1;
結果:
Abstract|14
standard|17
space|30
aroma|50
如果你想更新之前執行插入,只需插入一個字得分爲0,然後下面的更新將添加得分:
INSERT INTO Table1
SELECT Word, 0
FROM Table2
WHERE Table2.Word NOT IN (SELECT Word FROM Table1);
UPDATE Table1
SET Score = Score + (SELECT SUM(Score) FROM Table2 WHERE Table1.Word = Table2.Word)
WHERE Word IN (SELECT Word FROM Table2);
現在,Sqlite有一些特殊的語法來處理這些情況。例如,如果Word
是Table1
的主鍵,則可以使用此插入語句的變體:
INSERT OR IGNORE INTO Table1
SELECT Word, 0
FROM Table2