mysql外键代码怎么写 mysql外键使用( 三 )


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;
alter table products add
constraint fk_products_vendors foreign key (v_id)
references vendors(v_id)
on delete no action
on update cascade;
望采纳祝mysql外键代码怎么写你好运
关于mysql外键代码怎么写和mysql外键使用的介绍到此就结束了 , 不知道你从中找到你需要的信息了吗 ?如果你还想了解更多这方面的信息,记得收藏关注本站 。

推荐阅读