Merging two SQLite databases which both have junction tables

前端 未结 1 1768
醉酒成梦
醉酒成梦 2021-01-03 10:33

I got two SQLite databases which both have junction tables to describe the one-to-many relationship. Now these two DB need to be merged into a single one with some

1条回答
  •  借酒劲吻你
    2021-01-03 10:56

    If you don't care about duplicates, you could get the maximum ID from DB1, and add it to every ID in DB2. However, you said that name could be unique, so let's do this right.

    I'm assuming that all id columns are INTEGER PRIMARY KEY, i.e., autoincrementing.

    Open DB1, and attach DB2:

    ATTACH '...' AS db2;
    

    Copy over all fruits and juices that do not yet exist in DB1 (these get new IDs):

    INSERT INTO Fruit(name)
    SELECT name
    FROM db2.Fruit
    WHERE name NOT IN (SELECT name
                       FROM Fruit);
    INSERT INTO Juice(name)
    SELECT name
    FROM db2.Juice
    WHERE name NOT IN (SELECT name
                       FROM Juice);
    

    Now copy over the recipes, while looking up the new ID values through the corresponding name:

    INSERT INTO Recipe(juice_id, fruit_id)
    SELECT (SELECT id
            FROM Juice
            WHERE name = (SELECT name
                          FROM db2.Juice
                          WHERE id = Recipe2.juice_id)),
           (SELECT id
            FROM Fruit
            WHERE name = (SELECT name
                          FROM db2.Fruit
                          WHERE id = Recipe2.fruit_id))
    FROM db2.Recipe AS Recipe2;
    

    0 讨论(0)
提交回复
热议问题