Foreign key in the first table

前端 未结 2 1216
走了就别回头了
走了就别回头了 2021-01-24 14:28

I have a question about foreign keys.

How does it work when I want to add a foreign key to the first table that I make that references to the primary key of the second t

2条回答
  •  爱一瞬间的悲伤
    2021-01-24 15:08

    Either create the second table first. Or use alter table. That is, create the first table without the reference and then do:

    alter table table1 add constraint fk_table1_team
        foreign key (team_id) REFERENCES table2(team_id);
    

    The declaration for table1 would be:

    CREATE TABLE table1 (   
        name_id INT NOT NULL,
        team_id INT, 
        PRIMARY KEY(name_id)
    );
    

    The reference between the tables should be on the primary key and certainly not on a character column, if an integer is available.

提交回复
热议问题