MYSQL-primary key foreign key constraint

Primary key syntax:

Add it when creating a table to specify the column data type (can be combined with AUTO_INCREMENT)

PRIMARY KEY

The primary key should be short, uniquely identify the record, and never change.

Foreign key syntax:

The first column_name is the column name of the specified foreign key

table_name is the table name of the primary key

The second column_name is the primary key column name

FOREIGN KEY (column_name) REFERENCES table_name(column_name);

Example:

Create table:

CREATE TABLE student (
student_id INT AUTO_INCREMENT PRIMARY KEY,
student_name VARCHAR(20));

Create a student table with student_id as the auto-increment primary key

CREATE TABLE score 
(score_id INT,
v INT,
FOREIGN KEY(score_id) REFERENCES student(student_id));

Specify score_id as a foreign key and connect with the primary key

Insert primary key data

INSERT INTO student (student_name) VALUES ('zhangsan'),('lisi'),('wangwu');

Then we try to insert the data of the score table

 

 Insert the data with score_id 1 successfully

 Failed to insert score_id 4

This is the primary foreign key constraint. After the foreign key is associated with the primary key, only the same data as the primary key can be inserted.

options

  1. CASCADE:
    waterfall/series/cascading, which means that it changes with the change of the primary key. For example, if the student_id of a student in the primary key changes from 1 to 2, the student_id of all registered course records of the student will also change to 2 (note that the primary key is generally also Best never change, special cases are discussed here)
  2. RESTRICT / NO ACTION:
    Both are equivalent, and the effect is to prohibit changing or deleting the primary key. For example: for a course with a registration record, unless the registration and purchase record of the course is deleted first, the information of the course cannot be deleted in the courses table
  3. SET NULL:
    It means that when the primary key is changed or deleted, the corresponding foreign key becomes empty, and such a child table record has no corresponding primary key and corresponding parent table record (no parent), which is called an orphan record (orphan record) ), this is garbage data, let us not know who registered for the course or what course is registered, generally not used, it may be useful only in extremely special cases.

 

 

Guess you like

Origin blog.csdn.net/chara9885/article/details/131500941