Sql 交叉引用外键约束出错

Sql 交叉引用外键约束出错,sql,foreign-keys,Sql,Foreign Keys,当我试图在MySQL中创建表时,遇到了一个奇怪的问题 我想交叉引用两个多对多表,下面是我创建表的代码 create table teacher( t_id char(10) not null unique, name varchar(20) not null, sur_name varchar(20) not null, CONSTRAINT pk_teacher PRIMARY KEY(t_id)) create table student( s_id char(10) not nul

当我试图在MySQL中创建表时,遇到了一个奇怪的问题

我想交叉引用两个多对多表,下面是我创建表的代码

create table teacher(
t_id char(10) not null unique, 
name varchar(20) not null, 
sur_name varchar(20) not null, 
CONSTRAINT pk_teacher PRIMARY KEY(t_id))

create table student(
s_id char(10) not null unique,
name varchar(20) not null,
sur_name varchar(20) not null,
CONSTRAINT pk_student PRIMARY KEY(s_id))

create table teacher_student(
t_id char(10) not null,
s_id char(10) not null,
CONSTRAINT pk_teacher_student PRIMARY KEY(t_id, s_id))
为了添加外部约束,我使用了以下代码

ALTER TABLE teacher_student 
ADD CONSTRAINT fk_teacher_student FOREIGN KEY(s_id) REFERENCES student(s_id)
ALTER TABLE teacher_student 
ADD CONSTRAINT fk_student_teacher FOREIGN KEY(t_id) REFERENCES teacher(t_id)
ALTER TABLE student 
ADD CONSTRAINT fk_student_teacher_student 
FOREIGN KEY(s_id) REFERENCES teacher_student(s_id)
ALTER TABLE teacher 
ADD CONSTRAINT fk_teacher_teacher_student
FOREIGN KEY(t_id) REFERENCES teacher_student(t_id)
这很好,但如果我尝试以这样的不同顺序执行代码

ALTER TABLE student 
ADD CONSTRAINT fk_student_teacher_student 
FOREIGN KEY(s_id) REFERENCES teacher_student(s_id)
ALTER TABLE teacher 
ADD CONSTRAINT fk_teacher_teacher_student
FOREIGN KEY(t_id) REFERENCES teacher_student(t_id)
ALTER TABLE teacher_student 
ADD CONSTRAINT fk_teacher_student FOREIGN KEY(s_id) REFERENCES student(s_id)
ALTER TABLE teacher_student 
ADD CONSTRAINT fk_student_teacher FOREIGN KEY(t_id) REFERENCES teacher(t_id)
ALTER TABLE student
我有个例外

Can't create table 'test.#sql-44c_37' (errno: 150)
我的问题是,为什么订单很重要?这两种创建约束的方法有什么区别?谢谢

“我尝试以不同的顺序执行代码,就像这样”您没有不同的顺序,您有非常不同的约束。不能创建此类约束。 查看本文以了解更多信息


您的一些外键似乎没有任何意义

那些引用
student
teacher
fk\u teacher\u student
fk\u student\u teacher
的)的都可以。这实际上是一个典型的多对多表引用两个实体表中每个实体表的情况,这两个实体表的多对多关系正在被实现

现在,从这些表返回到多对多表,您的建议是什么?我承认我不能真正解释为什么外键是使用第一个脚本成功添加的,而使用另一个脚本失败的。很抱歉。尽管我有一些模糊的想法,但这并不是我回答的重点。关键是,您当前的设计将使您很难添加新数据。有了它,你就不能真正地添加,比如说,一个学生,而不添加新学生和现有教师之间的关系。这是因为
student
中的一行应该引用
teacher\u student
中的现有学生,但由于该学生是新学生,
teacher\u student
中还没有相应的行。新老师也是如此

<>请考虑放弃<代码> FKI学生教师>学生>代码>代码> FKI教师>学生>代码>。您的设计不需要它们。它们已经导致您解决了一个不必要的问题,并且将来可能会造成更多的麻烦