约束的作用,是用于保证 数据的完整性或者合理性的工具!
外键 :foreign key,当前表内,指向其他表的主键的字段,称之为外键!

外键约束:用于限制相关联的记录在逻辑上保证合理性的约束称之为外键约束!
约束,不是字段。
建立班级表

再创建学生表

看看删除班级的情况:

出现了不合理数据:
此时,可以通过增加 外键约束 的方式,来限制以上的操作!
增加外键
----
alter table 表名 add constraint 约束的名字 foreign key 外键索引名字 (外键字段名) references 关联表名 (关联字段) [操作]

再删除个试试:

注意:如果当前的数据,已经不符合所见约束关联,则创建失败!
删除外键
----
alter table table\_name drop foreign\_key 外键名字!
可以通过 show create table 查看 约束的名字:

注意,外键约束与索引的关系:
如果需要在某个字段上,增加外键约束,那么需要该字段也同样有索引!如果该字段上,没有索引,此时,mysql会自动在该字段上增加一个普通索引!

可以选择指定外键约束的名字:


注意上面的 外键约束自动建立的索引的名字,与 外键的名字相同!
总结:在创建时:
1, 外键 与 相应关联表的主键类型
2, 已有数据,必须满足约束条件才可以!
3, 可以使用 constraint 关键字,为外键约束起名字!
约束操作
----
在 对 父表(被关联的表)做操作时,有三种行为:
1, 严格限制,拒绝操作。restrict
2, 置 null,set null
3, 级联操作,cascade
以上三个行为操作,会在 主表记录被 删除 或者 更新时被使用!
on delete set null
on update cascade


更新时的级联操作:
只有在 关联表的主键发生变化时,才会影响到从表的关联字段的变化!

主表:被关联的
从表:发出关联的!
应该注意的问题:
关于,外键约束,只能在 当前的 mysql的的 innodb 表类型(引擎)下才会生效!

外键,站在 php程序的角度,用到的不多!
数据操作,DML,DATA Management Language