How to Set foreign key constraints and the role of foreign keys in MySQL

Source: Internet
Author: User

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:

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.