如何在创建新表时添加外键?

时间:2008-10-27 09:44:33

标签: mysql create-table

我有两个CREATE TABLE语句:

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

CREATE TABLE PAYMENT (
  id int(15) not null auto_increment
  Foreign Key(id) references GUEST(id),
  BillNr int(15) not null
);

第二个陈述中的问题是什么?它没有创建新表。

5 个答案:

答案 0 :(得分:11)

您的问题的答案几乎与this one的答案相同。

您需要在包含外键的表中指定包含主键的表的名称,以及主键字段的名称(使用“references”)。

This有一些代码显示如何自己创建外键,以及在CREATE TABLE中。

以下是其中一个较简单的例子:

CREATE TABLE parent (id INT NOT NULL,
   PRIMARY KEY (id)
) ENGINE=INNODB;
CREATE TABLE child (id INT, parent_id INT,
   INDEX par_ind (parent_id),
   FOREIGN KEY (parent_id) REFERENCES parent(id)
   ON DELETE CASCADE
) ENGINE=INNODB;

答案 1 :(得分:3)

我建议为付款表设置一个唯一的密钥。在它的一边,外键不应该是auto_increment,因为它引用了一个已经存在的密钥。

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;

答案 2 :(得分:0)

确保您将InnoDB引擎用于数据库或两个表。来自MySQL参考:

  

对于InnoDB以外的存储引擎,   MySQL服务器解析FOREIGN KEY   但是,CREATE TABLE语句中的语法   不使用或存储它。

答案 3 :(得分:0)

create table course(ccode int(2) primary key,course varchar(10));

create table student1(rollno int(5) primary key,name varchar(10),coursecode int(2) not 
null,mark1 int(3),mark2 int(3),foreign key(coursecode) references course(ccode));

答案 4 :(得分:-1)

int(15)not null

之间应该有空格