导航

学生、老师、课程表、成绩表演示数据库使用

Posted on 2015-12-11 00:02  Morya  阅读(1076)  评论(0编辑  收藏  举报

学生、老师、课程表、成绩表演示数据库使用

数据库的select,insert,delete,update大家都会。

但是,等到复杂到学生、老师、课程表、成绩表的时候,我却是一直糊涂着,
直到最近实在是需要用到,才下功夫啃下这个小难题。

前提

首先,来申明一下前提。

-   学生有姓名、性别
-   老师有姓名、性别
-   学生可以选修不同的课程
-   学生对每一门选修的课程有分数统计

sql示例


CREATE TABLE `student` (
    `sid` int(11) NOT NULL,
    `sname` varchar(20) DEFAULT NULL,
    `ssex` smallint(6) DEFAULT NULL,
    PRIMARY KEY (`sid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE `teacher` (
    `tid` int(11) NOT NULL,
    `tname` varchar(20) DEFAULT NULL,
    PRIMARY KEY (`tid`),
    KEY `idx_teacher_name` (`tname`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE `course` (
    `cid` int(11) NOT NULL,
    `cname` varchar(32) DEFAULT NULL,
    `tid` int(11) DEFAULT NULL,
    PRIMARY KEY (`cid`),
    KEY `tid` (`tid`),
    CONSTRAINT `course_ibfk_1` FOREIGN KEY (`tid`) REFERENCES `teacher` (`tid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8

CREATE TABLE `score` (
    `sid` int(11) DEFAULT NULL,
    `cid` int(11) DEFAULT NULL,
    `value` int(11) DEFAULT NULL,
    KEY `sid` (`sid`),
    KEY `cid` (`cid`),
    CONSTRAINT `score_ibfk_1` FOREIGN KEY (`sid`) REFERENCES `student` (`sid`),
    CONSTRAINT `score_ibfk_2` FOREIGN KEY (`cid`) REFERENCES `course` (`cid`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;  
      

准备数据


insert into student select 0, '学生1', 1 union all select 1, '学生2', 1 union all select 2, '学生3', 2;
insert into teacher select 0, '孔子', 1 union all select 1, '孟子', 1 union all select 2, '李清照', 2;
insert into teacher select 0, '孔子' union all select 1, '孟子' union all select 2, '李清照';
insert into course values(0, '诗经', 0);
insert into course values(1, '道德经', 1);
insert into course values(2, '宋词', 2);

insert into score 
    select 0, 0, 99 union all 
    select 0, 1, 85 union all 
    select 0, 2, 65 union all 
    
    select 1, 0, 56 union all 
    select 1, 1, 68 union all
    select 1, 2, 77 union all 

    select 2, 0, 100 union all 
    select 2, 1, 120 union all 
    select 2, 2, 99
    ;

各种查询


-- 查询不及格学生
    
select a.sid, a.sname, b.value from student a, score b where b.value < 60 and a.sid = b.sid;
 
# 一看“学生2”就是那种坏学生 就没几个考好的。。。
+-----+---------+-------+
| sid | sname   | value |
+-----+---------+-------+
|   1 | 学生2   |    55 |
|   1 | 学生2   |    56 |
+-----+---------+-------+