zoukankan      html  css  js  c++  java
  • mysql学习笔记:集合运算并交差,其他

    总结一下今天数据库课堂上的所学2333

    1.

    SQL语言实践中,集合运算的实现方法,推荐顺序如下:

    运算:union

    运算:in, exists, intersect(很多DBMS基本上不支持ing qwq)-------->"同时"

    运算:not in, not exists, except, minus

    还有一种运算我在这也写一写哉2333,除法运算:not exists ... not exists...

    2.像老师提的那样要学会尽量一题多做,扩展思维!

    看这道题:查询选修了数据库课程的学生学号和姓名

    分析:可以用连接运算;也可以来2层嵌套查询,3层嵌套查询搞一波;也可以用存在量词exists实现查询之

    参考代码记录如下:

    select sc.sno,sname
    from student,c,sc
    where student.sno=sc.sno and sc.cno=c.cno and cname='数据库';
    
    select sno,sname from student
    where sno in (select sno from sc
    where cno in (select cno from c where cname='数据库'));
    
    select sno,sname from student
    where sno in (select sno from sc,c where sc.cno=c.cno and cname='数据库'); 
    
    /*exists实现*/
    select sno,sname from student
    where exists (select * from sc,c where sc.cno=c.cno and sc.sno=student.sno and cname='数据库'); 
    /*尽量能去拓展几种写法,从计算效率来说,连接查询效率大*/
    

      

    3.讨论一下集合交运算

    用in实现之:

    /*查询同时选择了1号课程和2号课程的学生的学号*/
    select sno
    from sc 
    where cno='1' 
    and sno in(	/*用in间接实现交运算*/
    select sno
    from sc
    where cno='2');
    

      用 exists  相关子查询实现之:

    /*查询同时选择了1号课程和2号课程的学生的学号*/
    select sno
    from sc as a
    where cno='1'
    and exists (/*exists交运算*/
    select * 
    from sc as b
    where cno='2'
    and b.sno=a.sno);
    /*exists代表存在量词,it just returns true or false*/
    

      

    差运算也是很相似的,接下来:求选修了1号课程但没有选修2号课程的学生学号

    用 not in 实现:

    /*查询选择了1号课程但没有选择2号课程的学生的学号*/
    select sno
    from sc 
    where cno='1' 
    and sno not in(	/*用not in间接实现差运算*/
    select sno
    from sc
    where cno='2');

    差运算我自己还是觉得拿not in来用香呀2333,当然not exists实现也要去比较熟练的掌握之,2333!

    用 not exists实现:

    /*not exists实现差运算*/
    /*查询选择了1号课程但没有选择2号课程的学生的学号*/
    select sno
    from sc as a
    where cno='1' 
    and not exists
    (select *
    from sc as b
    where cno='2'
    and b.sno=a.sno);
    select * from sc;

    3.用nort exists   not exists实现除运算,解决集合包含这样的查询,今天上午写的一些代码搬过来拉拉啦2333

    /*查询选修1号学生选修的所有课程的学生学号*/
    select distinct sno from sc as a where not exists
    (select * from sc as b where b.sno='1' and not exists
    (select * from sc as c where c.sno=a.sno and c.cno=b.cno)); 
    
    /*选了所有课程的学生学号*/
    select sno from student  where not exists
    (select * from c where not exists
    (select * from sc  where sno=student.sno and cno=c.cno)); 
    

      

  • 相关阅读:
    centos7下磁盘空间调整
    centos7下 查看CPU、内存、磁盘的使用情况
    centos7中Spark集群的安装与配置(Hadoop2.6.5+spark2.3.3)
    linux下mysql ---- Host '' is not allowed to connect to this MySQL server
    11-1、多线程
    10-2、对象的序列化和反序列化
    9-1、注解
    8-1、泛型
    7-1、集合
    6-1、异常处理
  • 原文地址:https://www.cnblogs.com/dragondragon/p/12489368.html
Copyright © 2011-2022 走看看