通过给mysql的表字段添加外键约束,可以有效的保持数据的一致性和完整性,数据就不会很容易出问题。
1、创建表时直接创建外键约束
create table books(
bookid number(10) not null primary key,
bookname varchar2(20) not null,
price number(10,2),
categoryid number(10) not null references category(id) --外键约束
);
备注:必须先创建参照表,才能在创建外键约束,即必须现有表category,再有book
2、先创建表,表创建成功后,单独添加外键约束
create table books(
bookid number(10) not null primary key,
bookname varchar2(20) not null,
price number(10,2),
categoryid number(10) not null
);
alter table books add constraint fk_book_categoryid foreign key(categoryid ) references category(id);
以上的2种方式就是目前在mysql中添加外键约束的方式,希望今后大家在使用关联表时,可以给表的某些字段添加外键约束,使数据能够保持完整性。
相关文章:
mysql外键约束ondelete和onupdate的使用_mysql
mysql外键约束的禁用与启用命令分享
mysql外键约束_mysql
以上就是mysql创建外键约束的两种方式的详细内容。