Mysql外键

2018-09-30  本文已影响0人  Alisallon

只有InnoDB存储引擎才支持外键

有两张表:

create table essay(
  id bigint auto_increment comment 'id' primary key,
  title varchar(255) default '' not null comment '标题',
  comment varchar(255) default '' not null comment '备注',
  type int(1) default '0' not null comment '类型(0:type1 1:type2)',
  c_time datetime not null comment '创建时间'
)
engine = InnoDB
charset = utf8;

create table user(
  id bigint auto_increment comment 'id' primary key,
  name varchar(255) default '' not null comment '名称',
  essay_id bigint null,
  #方式1:创建外键约束
  constraint FK_ESSAY_ID foreign key (essay_id) references essay(id)
)
engine = InnoDB
charset = utf8;

创建外键

方式1:

如上面创建表的语句:

constraint FK_ESSAY_ID foreign key (essay_id) references essay(id)
方式2:
# on delete/update XXXXX
# 上面的XXXXX表示外键约束方式,有下面4种:
# cascade:删除/更新父表的某条记录,子表中引用该值的记录会自动被删除/更新
# no action:如果子表中有匹配的记录,则不允许对父表对应候选键进行update/delete操作
# restrict:同no action,如果子表引用父表的某个字段的值,那么不允许直接删除父表的该值
# set null:在父表上update/delete记录时,将子表上匹配记录的列设为null 要注意子表的外键列不能为not null
alter table user add constraint FK_ESSAY_ID foreign key (essay_id) references essay(id) on delete cascade;

删除外键

alter table user drop foreign key FK_ESSAY_ID ;
上一篇 下一篇

猜你喜欢

热点阅读