首先创建班级表,因为班级跟学生为一对多关系,先创建班级表能在学生表中插入外键
班级表
CREATE TABLE banji(
id INT PRIMARY KEY AUTO_INCREMENT,
`name` VARCHAR(10) NOT NULL
);
INSERT INTO banji(`name`)VALUES('class1'),('class2');
SELECT * FROM banji;
CREATE TABLE student(
id INT PRIMARY KEY AUTO_INCREMENT,
`name` VARCHAR(10) NOT NULL,
age INT,
gender CHAR(1),
banji_id INT,
FOREIGN KEY(banji_id) REFERENCES banji(id)
);
INSERT INTO student(`name`,age,gender,banji_id)
VALUES('张三',20,'男',1),('李四',21,'男',2),('王五',20,'女',1);
SELECT * FROM student;
创建课程表
CREATE TABLE course(
id INT PRIMARY KEY AUTO_INCREMENT,
NAME CHAR(10)NOT NULL,
credit INT
);
INSERT INTO course(NAME,credit) VALUES('Chinese',5),('Math',4),(English,4);
SELECT * FROM course;
创建班级课程表
班级跟课程之间的关系为多对多
创建班级课程表,将banji_id,course_id作为外键,称为联合主键
CREATE TABLE banji_course(
banji_id INT,
course_id INT,
PRIMARY KEY(banji_id,course_id),
FOREIGN KEY(banji_id) REFERENCES banji(id),
FOREIGN KEY(course_id) REFERENCES course(id)
);
INSERT INTO banji_course(banji_id,course_id) VALUES(1,1),(1,3),(2,1),(2,2),(2,3);
SELECT * FROM banji_course;
他们之间的关系