外键约束作用
外键约束:对外键字段的值进行更新和插入时会和引用表中字段的数据进行验证,数据如果不合法则更新和插入会失败,保证数据的有效性。
对于已经存在的字段添加外键约束
-- 为category_id字段添加外键约束
alter table articles add foreign key(category_id) references categories(id);
注意会提示错误:Foreign key constraint is incorrectly formed
,这是因为两个字段的数据类型不一样
- 将 articles 表中的 category_id,改为 unsigned
- 将 articles 表中 category_id 的数据,改为能与 article 表中 id 对应得上的数据。
在创建数据表时设置外键约束
-- 创建学校表
create table school(
id int not null primary key auto_increment,
...