本教程操作环境:windows10系统、mysql8.0.22版本、Dell G3电脑。
 
  语法:
 
  SELECT 字段 FROM table WHERE EXISTS (subquery);
  参数:
 
  subquery是一个受限的SELECT语句(不允许有COMPUTE子句和INTO关键字)
 
  示例:
 
  SELECT * FROM A WHERE EXISTS (SELECT 1 FROM B WHERE B.id = A.id);
  
  下面通过几个示例来说明一下EXISTS和NOT EXISTS的用法,及其与IN和NOT IN的区别
 
  1、在子查询中使用NULL,仍然返回结果集
 
  下面三种情况返回数据相同,都会返回student表的所有数据:
 
  select * from student;
  select * from student where exists (select 1);
  select * from student where exists (select null);
  2、EXISTS子查询返回的是一个布尔值true或false
 
  EXISTS用于检查子查询是否至少会返回一行数据,该子查询实际上并不返回任何数据,而是返回布尔值true或false,EXISTS指定一个子查询,检测行的存在。
 
  EXISTS只在乎子查询中是否有记录,与具体的结果集无关,所以下面示例中,子查询中的select sno也可以换成select cno或者select 1,查询出的结果集是一样的。
 
  查询所有选修了课程号为3的学生:
 
  select * from student a
  where exists (select sno from student_course_relation b where b.cno=3 and b.sno=a.sno);
  select * from student a
  where exists (select cno from student_course_relation b where b.cno=3 and b.sno=a.sno);
  select * from student a
  where exists (select 1 from student_course_relation b where b.cno=3 and b.sno=a.sno);
  以上是“mysql中exists怎么用”这篇文章的所有内容,感谢各位的阅读!

dawei

【声明】:站长网内容转载自互联网,其相关言论仅代表作者个人观点绝非权威,不代表本站立场。如您发现内容存在版权问题,请提交相关链接至邮箱:bqsm@foxmail.com,我们将及时予以处理。