sql中exists的常用用法
创始人
2025-05-31 12:01:21
0

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 = '跳舞');
  1. 先将student表的第一行数据带入后面的子查询,通过sudent_no关联有数据,hobbies为跳舞,即返回true,这样结果集将会有student表的第一行数据;

  1. 然后将student表的第二行数据带入后面的子查询,通过sudent_no关联有数据,hobbies为跳舞,即返回true,这样结果集将会有student表的第二行数据;

  1. 继续将student表的第三行数据带入后面的子查询,通过sudent_no关联有数据,hobbies为唱歌,不满足此条件,即返回false,这样结果集不会有student表的第三行数据;

  1. 综上,结果集将会返回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的基本用法及其执行过程。生活就要不断的学习,温故而知新。加油,美好的风景一直在路上!

相关内容

热门资讯

【PdgCntEditor】解... 一、问题背景 大部分的图书对应的PDF,目录中的页码并非PDF中直接索引的页码...
修复 爱普生 EPSON L4... L4151 L4153 L4156 L4158 L4163 L4165 L4166 L4168 L4...
在Word、WPS中插入AxM... 引言 我最近需要写一些文章,在排版时发现AxMath插入的公式竟然会导致行间距异常&#...
监控摄像头接入GB28181平... 流程简介将监控摄像头的视频在网站和APP中直播,要解决的几个问题是:1&...
protocol buffer... 目录 目录 什么是protocol buffer 1.protobuf 1.1安装  1.2使用...
Windows10添加群晖磁盘... 在使用群晖NAS时,我们需要通过本地映射的方式把NAS映射成本地的一块磁盘使用。 通过...
牛客计算器的改良(Python... 文章目录1.题目描述2.输入描述:3.输出描述:4.示例15.分析6.代码7.结语 链接࿱...
【前端】‘??‘与‘||‘有什... 0 问题 经常写const data = res.data.a ?? ''或者const d...
正大杯|市调大赛|2023备赛... 关键信息 同时随着精细化养宠趋势的深入,宠物消费类目日渐丰富。 本报告通过 Niuco...
文本生成视频Make-A-Vi... Meta公司(原Facebook)在今年9月29日首次推出一款人工智能系...