創建一個外鍵:
第一種方法可以在創建表的時候創建:
create table student (
id int primary key auto_increment,
name varchar(10),
c_id int ,
constraint student_foregin foreign key(c_id) references class(c_id)
);
紅色這部分是外鍵的名字,刪除外鍵的時候用用到,如果自己不顯示地取一個名字,系統會默認取!
第二種方法就是在表已經創建好的時候創建:
alter table student add foreign key student(c_id) references class(c_id);
刪除一個外鍵:
前面已經說過,在一張表中,外鍵是有自己名字的,而不是字段的名字!如果我們不顯示地名字字段名字,可以通過
命令行去看一下外鍵的名字:show create table 表名。
刪除表的外鍵的
alter table student drop foreign key student_foregin;