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

前端 未结 11 1428
旧时难觅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.

    0 讨论(0)
  • 2020-11-27 12:58

    If you use Db Browser for sqlite ,then it will be easy for you to modify the table. you can add foreign key in existing table without writing a query.

    • Open your database in Db browser,
    • Just right click on table and click modify,
    • At there scroll to foreign key column,
    • double click on field which you want to alter,
    • Then select table and it's field and click ok.

    that's it. You successfully added foreign key in existing table.

    0 讨论(0)
  • 2020-11-27 12:59

    Create a foreign key to the existing SQLLite table:

    There is no direct way to do that for SQL LITE. Run the below query to recreate STUDENTS table with foreign keys. Run the query after creating initial STUDENTS table and inserting data into the table.

    CREATE TABLE    STUDENTS    (       
        STUDENT_ID  INT NOT NULL,   
        FIRST_NAME  VARCHAR(50) NOT NULL,   
        LAST_NAME   VARCHAR(50) NOT NULL,   
        CITY    VARCHAR(50) DEFAULT NULL,   
        BADGE_NO    INT DEFAULT NULL
        PRIMARY KEY(STUDENT_ID) 
    );
    

    Insert data into STUDENTS table.

    Then Add FOREIGN KEY : making BADGE_NO as the foreign key of same STUDENTS table

    BEGIN;
    CREATE TABLE STUDENTS_new (
        STUDENT_ID  INT NOT NULL,   
        FIRST_NAME  VARCHAR(50) NOT NULL,   
        LAST_NAME   VARCHAR(50) NOT NULL,   
        CITY    VARCHAR(50) DEFAULT NULL,   
        BADGE_NO    INT DEFAULT NULL,
        PRIMARY KEY(STUDENT_ID) ,
        FOREIGN KEY(BADGE_NO) REFERENCES STUDENTS(STUDENT_ID)   
    );
    INSERT INTO STUDENTS_new SELECT * FROM STUDENTS;
    DROP TABLE STUDENTS;
    ALTER TABLE STUDENTS_new RENAME TO STUDENTS;
    COMMIT;
    

    we can add the foreign key from any other table as well.

    0 讨论(0)
  • 2020-11-27 12:59

    First add a column in child table Cid as int then alter table with the code below. This way you can add the foreign key Cid as the primary key of parent table and use it as the foreign key in child table ... hope it will help you as it is good for me:

    ALTER TABLE [child] 
      ADD CONSTRAINT [CId] 
      FOREIGN KEY ([CId]) 
      REFERENCES [Parent]([CId]) 
      ON DELETE CASCADE ON UPDATE NO ACTION;
    GO
    
    0 讨论(0)
  • 2020-11-27 13:02

    Please check https://www.sqlite.org/lang_altertable.html#otheralter

    The only schema altering commands directly supported by SQLite are the "rename table" and "add column" commands shown above. However, applications can make other arbitrary changes to the format of a table using a simple sequence of operations. The steps to make arbitrary changes to the schema design of some table X are as follows:

    1. If foreign key constraints are enabled, disable them using PRAGMA foreign_keys=OFF.
    2. Start a transaction.
    3. Remember the format of all indexes and triggers associated with table X. This information will be needed in step 8 below. One way to do this is to run a query like the following: SELECT type, sql FROM sqlite_master WHERE tbl_name='X'.
    4. Use CREATE TABLE to construct a new table "new_X" that is in the desired revised format of table X. Make sure that the name "new_X" does not collide with any existing table name, of course.
    5. Transfer content from X into new_X using a statement like: INSERT INTO new_X SELECT ... FROM X.
    6. Drop the old table X: DROP TABLE X.
    7. Change the name of new_X to X using: ALTER TABLE new_X RENAME TO X.
    8. Use CREATE INDEX and CREATE TRIGGER to reconstruct indexes and triggers associated with table X. Perhaps use the old format of the triggers and indexes saved from step 3 above as a guide, making changes as appropriate for the alteration.
    9. If any views refer to table X in a way that is affected by the schema change, then drop those views using DROP VIEW and recreate them with whatever changes are necessary to accommodate the schema change using CREATE VIEW.
    10. If foreign key constraints were originally enabled then run PRAGMA foreign_key_check to verify that the schema change did not break any foreign key constraints.
    11. Commit the transaction started in step 2.
    12. If foreign keys constraints were originally enabled, reenable them now.

    The procedure above is completely general and will work even if the schema change causes the information stored in the table to change. So the full procedure above is appropriate for dropping a column, changing the order of columns, adding or removing a UNIQUE constraint or PRIMARY KEY, adding CHECK or FOREIGN KEY or NOT NULL constraints, or changing the datatype for a column, for example.

    0 讨论(0)
  • 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);
    
    0 讨论(0)
提交回复
热议问题