exists中子查询结果集非空,则exists子查询返回true。如果exists子查询结果集为空,则exists子查询返回false。在平常的开发工作中,经常会用到exists,那么它应该如何使用呢?
1:查询兴趣爱好为跳舞的同学姓名及住址:
select st.name,st.address from student st
where EXISTS
(select * from student_info sf where
sf.student_no = st.student_no
and sf.hobbies = '跳舞');

2:查询兴趣爱好不是跳舞的同学姓名及住址:
select st.name,st.address from student st
where NOT EXISTS
(select * from student_info sf where
sf.student_no = st.student_no
and sf.hobbies = '跳舞');

3:exists的执行过程:
带exists的子查询不返回任何数据,返回值为boolean值,为逻辑真值,即true,或者为逻辑假值,即false。
student表:

student_info表:

select st.name,st.address from student st
where EXISTS
(select * from student_info sf where
sf.student_no = st.student_no
and sf.hobbies = '跳舞');
先将student表的第一行数据带入后面的子查询,通过sudent_no关联有数据,hobbies为跳舞,即返回true,这样结果集将会有student表的第一行数据;
然后将student表的第二行数据带入后面的子查询,通过sudent_no关联有数据,hobbies为跳舞,即返回true,这样结果集将会有student表的第二行数据;
继续将student表的第三行数据带入后面的子查询,通过sudent_no关联有数据,hobbies为唱歌,不满足此条件,即返回false,这样结果集不会有student表的第三行数据;
综上,结果集将会返回student表的前两行数据,第三条数据不符合条件。
4:查询兴趣爱好为跳舞和唱歌的同学名字及住址:
用in关键字:
select st.name,st.address from student st
where EXISTS
(select * from student_info sf where
sf.student_no = st.student_no
and sf.hobbies in ("唱歌","跳舞")
);
用find_in_set关键字:
select st.name,st.address from student st
where EXISTS
(select * from student_info sf where
sf.student_no = st.student_no
and FIND_IN_SET(sf.hobbies,"唱歌,跳舞")
);

以上为exists的基本用法及其执行过程。生活就要不断的学习,温故而知新。加油,美好的风景一直在路上!