美文网首页
数据库的增删改查

数据库的增删改查

作者: HannahLi_9f1c | 来源:发表于2018-11-01 17:42 被阅读0次

    这里使用的是postgres,和mysql有一些区别。

    1.select语句,最难的一种

    数据库里面有三张表


    1.查询课程名中出现了“%”的课程

    select *   from course  where cname like '%!%%' escape '!';


    2.查询没有选1号课程的学生的学号和姓名

    select sno, sname  from student  where sno not in  ( select sno     from sc   where cno='1');


    3.查询选了2号课程和3号课程的学生的姓名。

    select sname  from student where sno in ( select sno    from sc  where cno='2')  and sno in  ( select sno  from sc  where cno='3');


    4.查询所有没有被选过的课程。

    select *   from course c  where not exists  (select *    from SC     where c.cno=SC.cno);


    相关子查询EXISTS代表存在量词彐。带有EXISTS谓词的子查询不返回任何实际数据,它只产生逻辑真值“true”或逻辑假值“false”,这道题也就是找这样的课程,它没有在选课课程中出现过,也就是说没有被人选过。也可以写成:

    select *  from course  where cno not in  ( select cno from SC);

    5.查询各选课学生的学号,姓名,选课门数和平均成绩;

    select s.sno, sname, count(*), avg(grade)  from student s, sc  where s.sno=sc.sno  group by s.sno, sname;


    这里先进行连接查询,然后再根据学生学号、名字进行分组,这样才能统计出学生的选课情况,比如说选课门数。


    6.查询选课门数在2门以上(含2门)的学生中平均成绩最高的学生的学号;

    select sno  from sc  group by sno   having count(*)>=2 and avg(grade)>=all   (select avg(grade)     from sc    group by sno   having count(*)>=2);

    all,就是表示大于所有

    having子句只能用于grop by中


    7.查询选修2号课程的成绩最高的学生的学号和姓名;

    select s.sno, sname  from student s, sc  where s.sno=sc.sno and cno='2' and grade=    (select max(grade)   from sc    where cno='2');


    8.查询选课总学分最多的学生的姓名及其选课总学分。

    select s.name, sum(credit) from student s, SC, course c  where s.sno=SC.sno and c.cno=SC.cno  group by s.id, s.name    having sum (credit) >= all    (select sum (credit)    from SC, course c    where c.cno=SC.cno   group by sno);

    先进行三表连接,然后按学生学号和名字分组,选出总学分大于其他所有学生的学生名字和他的总学分。


    9.王五”所选查询选了“所有课程的学生的学号和姓名。

    select id, name  from student s  where not exists  ((select cno   from student s, SC   where s.sno=SC.sno and s.name='王五‘)   except   (select cno    from SC   where s.sno=SC.sno));

    10.查询选了其所在系开设的所有课程的学生姓名

    select id, name  from student s  where not exists  ((select c.cno   from course c    where s.sdept=c.sdept)   except   (select cno   from SC    where s.sno=SC.sno));

    相关文章

      网友评论

          本文标题:数据库的增删改查

          本文链接:https://www.haomeiwen.com/subject/xeixxqtx.html