如何使用SQL同步两个SQLite表?

时间:2016-10-21 13:27:14

标签: sql sqlite

我有两个表都有PhraseId作为键:

 Phrase containing 
        PhraseId, name and score column
 PhraseSource containing 
        PhraseId and name column

在更新期间填充PhraseSource表,它可能包含更少,相同或更多行。

有没有办法

  1. 如果新行存在于PhraseSource但不存在Phrase
  2. ,则将新行复制到Phrase表中
  3. 更新短语表中PhraseSource和Phrase
  4. 中名称不同的行
  5. 删除短语表中的行,其中这些行出现在短语中但不包含在短语来源
  6. 请注意,我需要在乐句表中保留乐谱数据。

1 个答案:

答案 0 :(得分:0)

易:

DELETE FROM Phrase;
INSERT INTO Phrase SELECT * FROM PhraseSource;

但如果更新不小,那么按照描述更有效:

INSERT INTO Phrase
SELECT * FROM PhraseSource
WHERE PhraseId NOT IN (SELECT PhraseId FROM Phrase);

UPDATE Phrase
SET name = (SELECT name
            FROM PhraseSource
            WHERE PhraseId = Phrase.PhraseId)
WHERE name <> (SELECT name
               FROM PhraseSource
               WHERE PhraseId = Phrase.PhraseId);

DELETE FROM Phrase
WHERE PhraseId NOT IN (SELECT PhraseId FROM PhraseSource);