外键mysql怎么写 mysql外键用法

mysql外键约束怎么写你好朋友
1.简介
外键表示一个表中外键mysql怎么写的一个字段被另外一个表中外键mysql怎么写的字段应用.外键对相关表中外键mysql怎么写的数据造成外键mysql怎么写了限制,使MySQL 能够保证参照完整性.
在MySQL 中,InnoDB 存储引擎支持外键.在一张表中,可以存在多个外键.
外键外键mysql怎么写的创建可以在创建表的时候创建,也可以在创建表之后增加(考虑数据的完整性问题).
父表:外键所指向的表.
字表:相对于父表,拥有外键的表.
2.语法
create 语法
create table table_name(
column_1,
column_2,
....
constraint constraint_name foreign key (column_name)
references parent_table(column_name)
on delete action
on update action
) engine=InnoDB default charset utf8;
constraint 子句允许为外键定义一个名称,如果不写,MySQL 自动生成一个名称
foreign key 子句指定子表中要应用父表的列.注意:MySQL 会自动创建一个基于外键的索引.
references 子句指定父表中的被引用字段.foreign key 和references 指定的列数必须相同.
on delete: 定义当父表中的记录被删除时,子表的记录应该执行的动作.action包括:
on delete restrict:(默认),父表不能删除一个已经被子表引用的记录.
on delete no action:等同与on delete restrict
on delete cascade: 级联模式,父表删除后,对应子表关联的数据也跟着被删除
on delete set null:置空模式,父表删除后,对应子表关联的外键值被设置为NULL,需要注意的是,如果子表的外键设置not null ,则不能使用这种模式,因为会相互冲突.
on update:定义父表中的记录更新时,子表的记录应该执行的动作.action 包括:
on updaterestrict:(默认),父表不能更新一个已经被子表引用的记录.
on update no action:等同与on delete restrict
on update cascade: 级联模式,父表更新后,对应子表关联的数据也跟着被更新
on update set null:置空模式,父表更新后,对应子表关联的外键值被设置为NULL,需要注意的是,如果子表的外键设置not null ,则不能使用这种模式.
alter 语法
-- 添加外键
alter table table_name add constraint constraint_name
foreign key column_name
references parent_table(column_name)
on delete action
on update action
-- 删除外键
alter table table_name drop constraint_name;
-- 如果没有显式的定义名字,可以使用如下命令获取
show create table table_name;
3.演示
构造两张表categoryes 和products.每个类别有多种产品,而每个产品只属于一个类别.
-- 设置 类别表 categoryes 和产品表 products
create table categoryes(
c_id int not null auto_increment,
c_name varchar(45) not null,
c_description text,
primary key (c_id)
) engine=InnoDB default charset utf8 comment '类别表';
create table products(
p_id int not null auto_increment,
p_name varchar(45) not null,
p_price decimal(8,4),
c_id int,
primary key (p_id),
constraint fk_products_categoryes
foreign key (c_id)
references categoryes(c_id)
on delete set null
on update cascade
) engine=InnoDB default charset utf8 comment '产品表';
在这两张表的基础上,新生成一张vendors 供应商表,并更新products字段
-- 新生成一张表 供应商 vendors ,并为 products 新添加字段 v_id 外键
-- 引用 vendors.v_id
create table vendors(
v_id int not null auto_increment,
v_name varchar(45),
primary key (v_id)
) engine=InnoDB default charset utf8 comment '供应商';
alter table products add column v_id int not null;

推荐阅读