为什么不能添加外键约束?

时间:2018-08-23 03:09:30

标签: mysql

当我创建了students表的外键时,就出现了问题。

cur.execute(

"""

CREATE TABLE teachers
(
 id int NOT NULL auto_increment  primary key comment 'ID',
 teacher_name varchar(255) comment '教师姓名',
 teacher_sex varchar(255) comment '教师性别',
 teacher_age varchar(255) comment '教师年龄',
 teacher_pay int comment '课时费',
 course_name varchar(255)  COMMENT '课程名称'
 )ENGINE=InnoDB ;

""")

cur.execute("ALTER TABLE teachers COMMENT = '教师表';")
cur.execute("ALTER TABLE teachers ADD INDEX for_index_name(course_name);")

cur.execute(
"""

CREATE TABLE courses
 (
  id int NOT NULL auto_increment  primary key comment 'ID',
  course_id int  COMMENT '课程编号',
  course_name varchar(255) COMMENT '课程名称',
  time varchar(255) comment '上课时间',
  UNIQUE (course_id),
  FOREIGN KEY (course_name) REFERENCES teachers(course_name) ON DELETE CASCADE
  )ENGINE=InnoDB;
""")

cur.execute("ALTER TABLE courses COMMENT = '课程表';")
cur.execute("ALTER TABLE courses ADD INDEX for_index_name(course_name);")

**cur.execute(

"""

CREATE TABLE students
(
id int NOT NULL auto_increment  primary key comment 'ID',
students_name varchar(255) comment '学生姓名',
students_sex varchar(255) comment '学生性别',
students_age varchar(255) comment '学生年龄',
teacher_name varchar(255) comment '教师姓名',
course_name varchar(255) COMMENT '课程名称',
KEY teachers (teacher_name),
constraint teachers FOREIGN KEY (teacher_name) references 
teachers(teacher_name) ON DELETE CASCADE,
KEY courses (course_name),
constraint courses FOREIGN KEY (course_name) references courses(course_name) 
)ENGINE=InnoDB;
""")**

cur.execute("ALTER TABLE students COMMENT = '学生表';")

1 个答案:

答案 0 :(得分:1)

问题来自constraint teachers FOREIGN KEY (teacher_name) references teachers(teacher_name) ON DELETE CASCADE,

由于teacher_name不是PRIMARY KEY并且没有索引。 DB拒绝FK。 只需在此列上添加索引:

ALTER TABLE teachers ADD INDEX for_index_teacher_name(teacher_name);

Fiddle with the correction on line 15


但是我建议您开始使用ID而不是名称。这样就不需要那些INDEX了,如果仅在表teacher中,则更容易更新teacher名称。

因此,您将拥有teacher_name,而不是courses中的ref_teacher int。并在FOREIGN KEY上添加teacher(id)。这是一个主键,因此不需要任何INDEX,并且绝不应该更新主键,因此更易于维护。

喜欢这个:

CREATE TABLE students
(
id int NOT NULL auto_increment  primary key comment 'ID',
students_name varchar(255) comment '学生姓名',
students_sex varchar(255) comment '学生性别',
students_age varchar(255) comment '学生年龄',
ref_teacher int comment '教师姓名',
ref_course int COMMENT '课程名称',
constraint teachers FOREIGN KEY (ref_teacher) references teachers(id) ON DELETE CASCADE,
constraint courses FOREIGN KEY (ref_course) references courses(id)
)ENGINE=InnoDB;

Fiddle with ID used for FK