當我嘗試在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
執行代碼我一個m得到例外
Can't create table 'test.#sql-44c_37' (errno: 150)
我的問題是,爲什麼順序很重要?這兩種創建約束的方式有什麼區別?謝謝