3
我在添加一些外键约束到我的MySQL数据库时遇到问题。例如,在本注册表(用于记录学生出席情况的考勤注册表)中,我希望将fk_unit_id和fk_student_id作为外键,引用Unit和Student中的主键。MySQL数据库无法添加外键
注册表:
CREATE TABLE IF NOT EXISTS register
(
fk_unit_id INT(4) NOT NULL,
fk_student_id INT(4) NOT NULL,
register_date DATE NOT NULL,
attendance CHAR(1) NOT NULL,
PRIMARY KEY (fk_unit_id, fk_student_id, register_date),
FOREIGN KEY (fk_unit_id) REFERENCES unit(unit_id),
FOREIGN KEY (fk_student_id) REFERENCES student(student_id)
);
学生表:
CREATE TABLE IF NOT EXISTS student
(
student_id INT(4) ZEROFILL NOT NULL AUTO_INCREMENT,
student_first_name VARCHAR(20) NOT NULL,
student_surname VARCHAR(20) NOT NULL,
student_dob DATE NOT NULL,
student_contact_no VARCHAR(11) NOT NULL,
student_email VARCHAR(30) NOT NULL,
student_address VARCHAR(50) NOT NULL,
student_image_name VARCHAR(30) NOT NULL,
PRIMARY KEY (student_id)
);
表单位:
CREATE TABLE IF NOT EXISTS unit
(
unit_id INT(4) ZEROFILL NOT NULL AUTO_INCREMENT,
unit_name VARCHAR(50) NOT NULL,
unit_day VARCHAR(10) NOT NULL,
unit_time VARCHAR (10) NOT NULL,
fk_course_code VARCHAR(4) NOT NULL,
fk_lecturer_id INT(4) NOT NULL,
PRIMARY KEY (unit_id),
FOREIGN KEY (fk_course_code) REFERENCES course(course_code),
FOREIGN KEY (fk_lecturer_id) REFERENCES lecturer(lecturer_id)
);
对于R ecord,fk_course_code可以和VARCHAR(4)的Course(course_code)一起工作,所以我想知道是否它不喜欢使用auto_increated主键作为外键?
编辑
我收到错误代码#1215 - 不能添加外键约束
任何帮助将非常感激!
mysql一般不关心字段是什么类型。您几乎可以将任何字段用作外键,但两个表中的字段定义必须几乎完全相同。例如您可以将'unsigned int'链接到'unsigned int',但不能将'int'链接到'bigint'或'varchar'链接到'text'。关于唯一的例外是子表中的字段可以为空,即使父字段为“非空”。 –
一名学生可以多次注册同一个单位吗?如果没有,那么我不认为这是正确的:在这种情况下,'PRIMARY KEY(fk_unit_id,fk_student_id,register_date)''你只需要'PRIMARY KEY(fk_unit_id,fk_student_id)'。 – Maximus2012
你怎么知道外键是不是工作?是否有任何错误消息,你得到? – Maximus2012