mysql创建外键约束的两种方式

通过给mysql的表字段添加外键约束,可以有效的保持数据的一致性和完整性,数据就不会很容易出问题。

这里以学生表和班级表为例。

如图

1、创建表时直接创建外键约束

create table student(
id  int  not null primary key,
name varchar(32) not null,
class_id  int  not null references class(id)     -- 外键约束
);

或者

create table student(
id  int  not null primary key,
name varchar(32) not null,
class_id  int  not null,
constraint   pk_class_id  foreign key (class_id) references  class(id)  -- 外键约束
);

备注:必须先创建参照表,才能在创建外键约束,即必须现有表class,再有student

2、先创建表,表创建成功后,单独添加外键约束

create table student(
id  int  not null primary key,
name varchar(32) not null,
class_id  int  not null
);
alter  table student  add constraint  fk_class_id  foreign key  (class_id)  references  class(id);

以上的2种方式就是目前在Mysql中添加外键约束的方式,希望今后大家在使用关联表时,可以给表的某些字段添加外键约束,使数据能够保持完整性。

posted @ 2023-03-06 17:24  羊脂玉净瓶  阅读(407)  评论(0)    收藏  举报