Home  >  Article  >  Database  >  Two ways to create foreign key constraints in Mysql

Two ways to create foreign key constraints in Mysql

亚连
亚连Original
2018-05-10 10:38:1413688browse

By adding foreign key constraints to mysql table fields, the consistency and integrity of the data can be effectively maintained, and the data will not be prone to problems.

1. Create foreign key constraints directly when creating a table

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)  --外键约束
);

Note: The reference table must be created first before foreign key constraints can be created. That is, there must be an existing table Category, and then there is book

2. Create the table first, and after the table is successfully created, add the foreign key constraints separately

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);

The above two methods This is the current way to add foreign key constraints in Mysql. I hope that when you use related tables in the future, you can add foreign key constraints to some fields of the table so that the data can maintain integrity.

Related articles:

The use of MySQL foreign key constraints OnDelete and OnUpdate_MySQL

MySQL foreign key Disabling and enabling command sharing of constraints

Mysql foreign key constraints_MySQL

The above is the detailed content of Two ways to create foreign key constraints in Mysql. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn