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

2025-10-26
网站建设限时活动促销

通过给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);

标签: mysql外键约束

本文地址:https://www.lifejia.cn/news/208785.html

免责声明:本站内容仅用于学习参考,信息和图片素材来源于互联网,如内容侵权与违规,请联系我们进行删除,我们将在三个工作日内处理。联系邮箱:cloudinto#qq.com(把#换成@)