/* Primary key cannot be null NULL, the primary key of a table can only be by one, a primary key is a unique UK/*
/*primary key (SNAME,SID) composite primary key can be controlled at the same time sname,sid less */
/* Foreign key FK is generally 2 tables, only support INNODB engine */
drop table teacher;
CREATE TABLE Teacher (
Tid smallint unsigned NOT NULL auto_increment primary key,
Tname varchar (10)
) Engine=innodb CharSet UTF8;
CREATE TABLE Student (
Sid int unsigned NOT NULL Auto_increment primary key,
Sname varchar (10),
Stid smallint unsigned,
Constraint FK foreign KEY (Stid) References teacher (TID)
) Engine=innodb CharSet UTF8;
CREATE TABLE Student (
Sid int unsigned NOT NULL Auto_increment primary key,
Sname varchar (10),
Stid smallint unsigned,
Constraint FK foreign KEY (Stid) References teacher (tid) on delete set NULL on update set null/* this kind of deletion, will only remove the teacher, let the student's substitute teacher empty * *
) Engine=innodb CharSet UTF8;
CREATE TABLE Student (
Sid int unsigned NOT NULL Auto_increment primary key,
Sname varchar (10),
Stid smallint unsigned,
Constraint FK foreign KEY (Stid) References teacher (tid) on delete set null/* this kind of deletion, will only remove the teacher, so that the student's substitute teacher is empty */
) Engine=innodb CharSet UTF8;
drop table student;
CREATE TABLE Student (
Sid int unsigned NOT NULL Auto_increment primary key,
Sname varchar (10),
Stid smallint unsigned,
Constraint FK foreign KEY (Stid) References teacher (tid) on delete cascade/* cascade Delete, remove the teacher at the same time, the student also deleted the * *
) Engine=innodb CharSet UTF8;
Insert into teacher values (null, ' Miss Li ');
Insert into teacher values (null, ' Miss Wang ');
Insert into teacher values (null, ' Miss Chen ');
Insert into teacher values (null, ' teacher ');
SELECT * from teacher;
Select Database ();
Use XX;
INSERT into student values (NULL, ' John Doe ', 4);
INSERT into student values (null, ' xiaoming ', 8);
INSERT into student values (null, ' Li ', 7);
INSERT into student values (null, ' small ', 6);
SELECT * from student;
/* Delete teacher, miss. Teacher, there is a substitute for the following student table so can not be deleted, no lessons to delete * *
Delete from teacher where tid=2;
Delete from teacher where tid=7;
/* Because there is a foreign key control in the student's table, delete the student form and delete the teacher's watch first.
drop table student;
MySQL FOREIGN key operation