数据库notexist
‘壹’ 数据库语言关于not exist的用法
卤煮你好,
答案写法很好,我看了很久才弄明白,但我认为有漏洞,实际应用的话应该需要完善
我先说我的写法,再解释答案的逻辑
我的:
select st.sno, st.sname
FROM student st
where exists(
select 1 from SC a join Cource b on a.Cno=b.Cno where a.Sno=st.Sno and
a.Cno in(3,5,8) having count(*)=3
)
或者
select st.sno, st.sname
FROM student st
where exists(
select 1 from SC where Sno=st.Sno and
Cno in(3,5,8) having count(*)=3
)
/*通过和上面的比较你可以发现其实Cource其实没有作用,但是第一种写法更加严密,因为可以判断SC中的Cno是不是有效的*/
-------分割线--------------------------
再来看看这个答案
SELECT student.sno, student.sname
FROM student
WHERE not exists(select course.cno
from course
where course.cno in (3,5,8) and not exists(select *
from sc
where student.sno=sc.sno and course.cno=sc.cno));
看起来很复杂,我们先来拆分下
因为sql 的查询和执行是逐条进行的,主体是从Student表中中选数据,我们假设Student中有【小明】这个人,如何判断小明是不是该出来呢,只要
select course.cno
from course
where course.cno in (3,5,8) and not exists(select *
from sc
where ‘小明’=sc.sno and course.cno=sc.cno)
这一大坨【不返回结果】即可,
这一坨
,select course.cno
from course
where course.cno in (3,5,8) and not exists(select *
from sc
where ‘小明’=sc.sno and course.cno=sc.cno)
意思就比较明确了(我这儿迷糊了好一阵子)
只要小明同时选修了3,5,8那么这段话就不返回结果,所以最终小明就出现了!
/*ps.题目有个地方我没太看明白,“3且5且8” 是指的是同时选修3,5,8呢还是同时选修3,5,8且只选修这三个。如果是后者这3个写法还要再加一句exists*/
----三段写法全部测试通过,卤煮可以尽情测试~要给分啊!!!!!!!!!!!!
‘贰’ mysql数据库,not exists 语句
在sql语言里"存在"exists子句是非常不好理解的。
exists子句有两种用法,一种为独立exists子查询,另一种是父子关联子查询。前者对父查询不构成筛选作用,子查询若果有记录存在的话则输出所有的父查询记录集,反之则父查询输出空记录集。后者会对父查询构成筛选作用,不使用not关键字的情况下输出父查询中与子查询的交集,而使用not时则输出父查询中与子查询的非交集。至于如何判断exists子查询属于独立还是父子关联查询,以及为什么父子关联exists子查询会对父查询构成筛选作用,解释起来需要很大的篇幅这里就不讲了。反正我们记住父子关联查询的最常用功能就是它可以求出两张表的交集或非交集(使用not关键字)和不使用group分组的情况下求出某张表的最大值或最小值。
现在回到题主的具体问题上,这个问题涉及到三张表,学生表student、选课表sc、课程表course。
提问要求列出选取了所有课程的学生名单。
下面是提问中给出的sql语句:
select sname from student
where not exists(
select * from course
where not exists(
select * from sc
where sno=student.sno
and cno=course.cno));
从该语句我们看到它使用了两个嵌套父子关联不存在判断not exists子句,显然是要通过求非交集的方法查出选修了所有课程的学生名单。
一个学生如果他至少有一门课程没有选修,那么他在课程表里就会存在与选课表的非交集,我们姑且称之为“未选所有课程学生名单子集”,它由内层的not exists选出
...
select * from course
where not exists(
select * from sc
sno=student.sno
and cno=course.cno) .
‘叁’ sql中 not exists的问题
那你这个查询结果应该是为空。
not exists 的用法是 没有返回结果 为真。
EXCEPT是指在第一个集合中存在,但是不存在于第二个集合中的数据。
你A系有没有被学生选择的课程。也就是说not exists是有返回值的。有返回值那表示1=0 所以为空
‘肆’ 怎么理解数据库中not exist
not exists 是取反逻辑,也就是里面查询没有结果集就是为真,如果有结果集就是为假。然后作为整体的条件拼接到着查询上
‘伍’ sql中not exists用法
恩,对的,其实写法很多
1、
select id from a where id not in (select id_no from b)
2、
select id from a
except
select id_no from b
‘陆’ 关于sql语句 (not exists)
not exits{ 是信息系 not exits(参加项目) }
为什么是 信息系参加项目的
-- 不存在(是信息系 不存在(参加项目))
选出 不是信息系里且不参加项目的人
选出 除过信息系里参加项目的人和其他系的什么什么
‘柒’ 数据库语言 not exists 是什么意思
就是不在这个范围的意思
select id
from table
where name not exists(select 1
from table
where name = 'aaa')
也许你看不懂这个1的意思,不过在使用EXISTS的时候,通常都会使用1,它代表所查询出来的集合,等同于select name。
整个例子的意思是:查询name不等于aaa的所有ID。
不明白再问我,谢谢!