创建3个表,分别是student、sc、Course表。其中只有student表可以插入数据,其余两个表无法插入数据
/**********************************************/
// 创建表
create table student(
-> Sno CHAR(9) PRIMARY KEY,
-> Sname CHAR(20) UNIQUE,
-> Ssex CHAR(2),
-> Sage SMALLINT,
-> Sdept CHAR(20));
create table Course(
-> Cno CHAR(4) PRIMARY KEY,
-> Cname CHAR(40) NOT NULL,
-> Cpno CHAR(4),
-> Ccredit SMALLINT,
-> FOREIGN KEY(Cpno)REFERENCES Course(Cno));
create table sc(
-> Sno CHAR(9),
-> Cno CHAR(4),
-> Grade SMALLINT,
-> PRIMARY KEY(Sno, Cno),
-> FOREIGN KEY(Sno)REFERENCES student(Sno),
-> FOREIGN KEY(Cno)REFERENCES Course(Cno));
/**********************************************/
// 插入数据到student表(成功)
mysql> insert into student values('201215121','李勇','男',20,'CS');
Query OK, 1 row affected (0.01 sec)
mysql> insert into student values('201215122','刘晨','女',19,'CS');
Query OK, 1 row affected (0.00 sec)
mysql> insert into student values('201215123','王敏','女',18,'MA');
Query OK, 1 row affected (0.01 sec)
mysql> insert into student values('201215125','张立','男',19,'IS');
Query OK, 1 row affected (0.01 sec)
/**********************************************/
// 插入数据到course表(错误)
mysql> insert into course values('1','数据库','5',4);
ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails (`learning`.`course`, CONSTRAINT `course_ibfk_1` FOREIGN KEY (`Cpno`) REFERENCES `course` (`Cno`))
mysql> insert into course values(1 ,'数据库','5',4);
ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails (`learning`.`course`, CONSTRAINT `course_ibfk_1` FOREIGN KEY (`Cpno`) REFERENCES `course` (`Cno`))
mysql> insert into course values('数据库',4);
ERROR 1136 (21S01): Column count doesn't match value count at row 1
mysql> insert into course(Cno, Cname, Cpno, Ccredit) values('1','数据库','5', 4);
ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails (`learning`.`course`, CONSTRAINT `course_ibfk_1` FOREIGN KEY (`Cpno`) REFERENCES `course` (`Cno`))
/**********************************************/
// 插入数据到sc表(错误)
mysql> insert into sc values('201215121','1',92);
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ')' at line 1
mysql> insert into sc values('201215121','2',85);
ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ')' at line 1
mysql> insert into sc values('201215121','1',NULL);
ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails (`learning`.`sc`, CONSTRAINT `sc_ibfk_2` FOREIGN KEY (`Cno`) REFERENCES `course` (`Cno`))
mysql> INSERT INTO SC(Sno, Cno) VALUES('201215121','1');
ERROR 1452 (23000): Cannot add or update a child row: a foreign key constraint fails (`learning`.`sc`, CONSTRAINT `sc_ibfk_2` FOREIGN KEY (`Cno`) REFERENCES `course` (`Cno`))