MYSQL-子查询

子查询是一个查询语句嵌套在另一个查询语句中。内层查询语句的结果,可以为外层查询语句提供查询条件。

子查询关键字:in、not in、any、all、exists、not exists

1.带in关键字的子查询

实例:
select * from employee where d_id in (select d_id from department)
not in与之相反。

2.带比较运算符的子查询

比较运算符包括=、!=、> 、>=、 <、 <=、 <>等

select id,name,score from computer_stu where score >= (select score from schoolarship where level = 1);

3.带exists关键字的子查询

exists表示存在。内层返回一个布尔值。当内层返回false,则不进行外层查询,返回空值;如果内层返回true,则进行外层查询。
select * from employee where exists (select d_name from department where d_id = 1003);
exists可以与其他查询条件一起使用,用and、or连接。
select * from employee where age > 25 and exists (select d_name from department where d_id = 1003);
not exists与exists正好相反。

4.带any关键字的子查询

any关键字表示满足其中任何一条件。只要满足内层查询语句返回结果中的任何一个,就可以通过该条件执行外层查询语句。

>any 表示大于任何一个值,=any表示等于任何一个值。

select * from computer_stu where score >= any (select score from scholarship);

5.带all关键字的子查询

all表示满足所有条件。只有满足内衬层查询语句返回的所有结果,才可以执行外层查询语句。
select * from computer_stu where score >= all (select score from scholarship);

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 一、mysql查询的五种子句 where(条件查询)、having(筛选)、group by(分组)、order ...
    化城阅读 1,659评论 0 9
  • 1. Java基础部分 基础部分的顺序:基本语法,类相关的语法,内部类的语法,继承相关的语法,异常的语法,线程的语...
    子非鱼_t_阅读 31,780评论 18 399
  • 一. Java基础部分.................................................
    wy_sure阅读 3,839评论 0 11
  • mysql的查询、子查询及连接查询 一、mysql查询的五种子句 where(条件查询)、having(筛选)、g...
    时芥蓝阅读 683评论 0 3
  • 不知道从何时起,感觉每天都处在焦虑中,恨不得每天早上五点就起床,将所有知识、付费产品都装入脑中…… 因为不想虚度光...
    JuanlanG阅读 251评论 3 3