How can I add a foreign key when creating a new table?

后端 未结 5 1780
刺人心
刺人心 2020-12-17 16:18

I have these two CREATE TABLE statements:

CREATE TABLE GUEST (
  id int(15) not null auto_increment PRIMARY KEY,
  GuestName char(25) not null
         


        
5条回答
  •  执念已碎
    2020-12-17 16:41

    I will suggest having a unique key for the payment table. On it's side, the foreign key should not be auto_increment as it refer to an already existing key.

    CREATE TABLE GUEST(
        id int(15) not null auto_increment PRIMARY KEY, 
        GuestName char(25) not null
    )  ENGINE=INNODB;
    
    CREATE TABLE PAYMENT(
        id int(15)not null auto_increment, 
        Guest_id int(15) not null, 
        INDEX G_id (Guest_id), 
        Foreign Key(Guest_id) references GUEST(id),
        BillNr int(15) not null
    )  ENGINE=INNODB;
    

提交回复
热议问题