How to Set foreign key constraints and the role of foreign keys in MySQL
1. The foreign key has two main functions:
One is to allow the database to ensure data integrity and consistency through foreign keys.
One is to increase the readability of the erimage.
2. Foreign key Configuration
1) create a master table with the following code:
# Create a table student and add various constraints
Create table student
(
Id int primary key, # primary key constraint
Name varchar (20), # unique constraint
Age int not null, # non-empty Constraint
Sex varchar (2 ),
Address varchar (20) default 'chongqing '# default Constraint
);
Create a score table by using a foreign key. The Code is as follows:
# Creating a score table
Create table score
(
Id int primary key,
Sid int,
China int,
History int,
English int,
Constraint FK_sid foreign key (sid) references student (id) # create a link through a foreign key
);
There are many ways to create a foreign key. The most common format for creating a foreign key is the appearance of the constraint FK _ *** foreign key (**) references link.
Delete foreign key:
Alter table drop foreign key 'foreign key name '.
Note:
You can use the constraint foreign key name foreign key... to delete a foreign key only when defining a foreign key.
This article permanently updates the link address: