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

前端 未结 11 1720
旧时难觅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 13:05

    You can add the constraint if you alter table and add the column that uses the constraint.

    First, create table without the parent_id:

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

    Then, alter table:

    ALTER TABLE child ADD COLUMN parent_id INTEGER REFERENCES parent(id);
    

提交回复
热议问题