How do I add a foreign key to an existing SQLite table?

前端 未结 11 1721
旧时难觅i
旧时难觅i 2020-11-27 12:44

I have the following table:

CREATE TABLE child( 
  id INTEGER PRIMARY KEY, 
  parent_id INTEGER, 
  description TEXT);

How do I add a forei

11条回答
  •  不知归路
    2020-11-27 12:53

    Basically you cannot but you can bypass the situation.

    The correct way to add the foreign key constraint to an existing table is the following command.

    db.execSQL("alter table child add column newCol integer REFERENCES parent(parent_Id)");
    

    Then copy the parent_Id data to the newCol and then delete the Parent_Id column. Hence, no need for temporary table.

提交回复
热议问题