MySQL 一个表群练习
# 建班级表
CREATE TABLE class(
cid INT PRIMARY KEY AUTO_INCREMENT,
caption VARCHAR(20) NOT NULL);
INSERT INTO class VALUES(0,'三年二班');
INSERT INTO class VALUES(0,'一年三班');
INSERT INTO class VALUES(0,'三年一班');
# 建学生表
CREATE TABLE student(
sid INT PRIMARY KEY AUTO_INCREMENT,
sname VARCHAR(20) NOT NULL,
gender ENUM('男', '女'),
class_id INT,
FOREIGN KEY (class_id) REFERENCES class(cid)
);
INSERT INTO student VALUES(0,'钢蛋',2,1);
INSERT INTO student VALUES(0,'铁锤',2,1);
INSERT INTO student VALUES(0,'山炮',1,2);
# 建老师表
CREATE TABLE teacher(
tid INT PRIMARY KEY AUTO_INCREMENT,
tname VARCHAR(20) NOT NULL
);
INSERT INTO teacher VALUES(0,'波多');
INSERT INTO teacher VALUES(0,'苍井');
INSERT INTO teacher VALUES(0,'饭岛');
# 建课程表
CREATE TABLE course(
cid INT PRIMARY KEY AUTO_INCREMENT,
cname VARCHAR(20) NOT NULL,
teacher_id INT NOT NULL,
FOREIGN KEY (teacher_id) REFERENCES teacher(tid)
);
INSERT INTO course VALUES(0,'生物',1);
INSERT INTO course VALUES(0,'体育',1);
INSERT INTO course VALUES(0,'物理',2);
# 建成绩表
CREATE TABLE score(
sid INT PRIMARY KEY AUTO_INCREMENT,
student_id INT NOT NULL,
course_id INT NOT NULL,
number DECIMAL(5,2),
FOREIGN KEY (student_id) REFERENCES student(sid)
ON UPDATE CASCADE
ON DELETE RESTRICT,
FOREIGN KEY (course_id) REFERENCES course(cid)
ON UPDATE CASCADE
ON DELETE RESTRICT
);
INSERT INTO score VALUE(0,1,1,60);
INSERT INTO score VALUE(0,1,2,59);
INSERT INTO score VALUE(0,2,2,100);