您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

mysql学习笔记:集合运算并交差,其他

bubuko 2022/1/25 20:05:51 mysql 字数 5835 阅读 855 来源 http://www.bubuko.com/infolist-5-1.html

总结一下今天数据库课堂上的所学2333 1. 在SQL语言实践中,集合运算的实现方法,推荐顺序如下: 并运算:union 交运算:in, exists, intersect(很多DBMS基本上不支持ing qwq) >"同时" 差运算:not in, not exists, except, minu ...

 

总结一下今天数据库课堂上的所学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)); 

  

 

mysql学习笔记:集合运算并交差,其他

原文:https://www.cnblogs.com/dragondragon/p/12489368.html


如果您也喜欢它,动动您的小指点个赞吧

除非注明,文章均由 laddyq.com 整理发布,欢迎转载。

转载请注明:
链接:http://laddyq.com
来源:laddyq.com
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。


联系我
置顶