mysql database to add the foreign key in several ways

Create a master table: Class

CREATE TABLE class(cid INT PRIMARY KEY AUTO_INCREMENT,

sname VARCHAR(15) NOT NULL)

INSERT INTO class VALUES (NULL, 'sixth grade class')
INSERT INTO class VALUES (NULL, 'six grade classes')

The first: // 1 added directly (bit of a problem) in the back of the property value

CREATE TABLE student(sid INT AUTO_INCREMENT,
sname VARCHAR(10) NOT NULL,
s_cid INT REFERENCES class(cid),
PRIMARY KEY(sid)
);

// Add the test data
INSERT INTO student VALUES (NULL, 'Wang sledgehammer', 2)
INSERT INTO student VALUES (NULL, 'Huhan San', 3) // constraint is not valid, of unknown origin
INSERT INTO student VALUES (NULL, 'lying trough ', 4) // not believe in a test

In this way, the test do not know why, actually added to it a WTF? Online Baidu to no avail, self-study group no reply to temporarily shelve here

The second: // Added at the end of the sql statement

CREATE TABLE student(
sid INT AUTO_INCREMENT,
sname VARCHAR(10),
s_cid INT,
PRIMARY KEY(sid),
FOREIGN KEY (s_cid) REFERENCES class(cid)
);

// insert test data
INSERT INTO student VALUES (NULL, 'Wang sledgehammer', 2)
INSERT INTO student VALUES (NULL, 'Hu Hansan', 3) // insert failed constraints into force

Foreign key constraint to take effect

Third: the use //3.fk

This is the value of the class to manually collect summary, understanding is not in place, some test or understand a little, fk_ child table table _ parent table

CREATE TABLE student(sid INT AUTO_INCREMENT,
sname VARCHAR(10) NOT NULL,
s_cid INT ,
PRIMARY KEY(sid),
CONSTRAINT fk_student_class FOREIGN KEY(s_cid) REFERENCES class(cid)
);

// test wave the OK
INSERT INTO Student VALUES (NULL, 'Wang sledgehammer', 2)
INSERT INTO Student VALUES (NULL, 'Hu Hansan', 3) // insert failed constraints into force

The fourth: // 4 after the construction of the table to add foreign key (teaching class content)

CREATE TABLE student(sid INT AUTO_INCREMENT,
sname VARCHAR(10) NOT NULL,
s_cid INT ,
PRIMARY KEY(sid)
);

// add foreign key constraint: ALTER TABLE student ADD FOREIGN KEY (s_cid) REFERENCES class (cid);

// test
INSERT INTO student VALUES (NULL, 'Wang sledgehammer', 2)
INSERT INTO student VALUES (NULL, 'Huhan San', 3) // constraint commencement insertion fails

Published 69 original articles · won praise 25 · views 20000 +

Guess you like

Origin blog.csdn.net/qq_40985788/article/details/85918199
Recommended