DROP TABLE IF EXISTS `person`;
CREATE TABLE `person` (
`id` INT NOT NULL AUTO_INCREMENT,
`person_name` VARCHAR(16) DEFAULT NULL UNIQUE,
PRIMARY KEY (`id`)
) ENGINE=INNODB DEFAULT CHARSET=utf8mb4;
DROP TABLE IF EXISTS `book`;
CREATE TABLE `book` (
`id` INT NOT NULL AUTO_INCREMENT,
`book_name` VARCHAR(50) DEFAULT NULL UNIQUE,
`person_id` INT NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=INNODB DEFAULT CHARSET=utf8mb4;
插入测试值
INSERT INTO `person`
VALUES (1,'Tom'),
(2,'Bob');
INSERT INTO `book`
VALUES (1,'JAVA从入门到入土',1),
(2,'WEB渗透从入门到入狱',1),
(3,'数据结构与算法',2),
(4,'平凡的世界',1);
通过在book
表中创建的person_id
字段,我们很容易通过连接表查询到个人与书籍的对应情况:
学生每天都要上课,而学生与课程之间的关系就是多对多的关系
一个学生要上好几门课,而每门课也会被多个学生上(额...好像有点奇怪)
因此我们需要建立三张表,其中有一张用来联系另外两张表
DROP TABLE IF EXISTS `student`;
CREATE TABLE `student` (
`id` INT NOT NULL AUTO_INCREMENT,
`student_name` VARCHAR(12) DEFAULT NULL UNIQUE,
PRIMARY KEY (`id`)
) ENGINE=INNODB DEFAULT CHARSET=utf8mb4;
DROP TABLE IF EXISTS `course`;
CREATE TABLE `course` (
`id` INT NOT NULL AUTO_INCREMENT,
`course_name` VARCHAR(30) DEFAULT NULL UNIQUE,
PRIMARY KEY (`id`)
) ENGINE=INNODB DEFAULT CHARSET=utf8mb4;
DROP TABLE IF EXISTS `student_course`;
CREATE TABLE `student_course` (
`student_id` INT NOT NULL,
`course_id` INT NOT NULL,
PRIMARY KEY (`student_id`,`course_id`),
FOREIGN KEY (`student_id`) REFERENCES `student` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
FOREIGN KEY (`course_id`) REFERENCES `course` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=INNODB DEFAULT CHARSET=utf8mb4;
INSERT INTO `student`
VALUES (1,'Tom'),
(2,'Bob');
INSERT INTO `course`
VALUES (1,'JAVA程序设计'),
(2,'大学物理'),
(3,'数据结构与算法'),
(4,'C++面向对象程序设计');
INSERT INTO `student_course`
VALUES (1,1),
(1,3),
(1,4),
(2,2),
(2,4);
连接查询每个学生要上哪些课以及每门课被哪些学生上:thinking:
OK,完结撒花