表创建错误无法添加外键约束

时间:2014-02-08 09:23:20

标签: mysql foreign-keys mysql-error-1064

我在创建外键时遇到问题。以下是我的询问:

CREATE TABLE supervisee
(
  supervisee_staff_id           VARCHAR(10) NOT NULL,
  supervisee_email_address      VARCHAR(40) NOT NULL,
  supervisee_name           VARCHAR(40) NOT NULL,
  PRIMARY KEY(supervisee_staff_id),
  FOREIGN KEY(academic_id) 
  REFERENCES academic_result(academic_result_id)
)

CREATE TABLE academic_result
(
  academic_result_id        INTEGER(6) NOT NULL AUTO_INCREMENT,
  PRIMARY KEY(academic_result_id)
)

你的任何帮助都会感激不尽,非常感谢! :)

1 个答案:

答案 0 :(得分:0)

你没有说出你收到的错误,但我发现了两个潜在的问题。您的外键列academic_id需要定义为自己的列以及FOREIGN KEY子句。其次,首先定义依赖(academic_result)表,以便在定义外键时,它可以引用。试试这个例子:

CREATE TABLE academic_result ( 
  academic_result_id INTEGER(6) NOT NULL AUTO_INCREMENT, 
  PRIMARY KEY(academic_result_id) 
);
CREATE TABLE supervisee ( 
  supervisee_staff_id VARCHAR(10) NOT NULL, 
  supervisee_email_address VARCHAR(40) NOT NULL, 
  supervisee_name VARCHAR(40) NOT NULL, 
  academic_id INTEGER(6),
  PRIMARY KEY(supervisee_staff_id), 
  FOREIGN KEY(academic_id) 
    REFERENCES academic_result(academic_result_id) 
);