您的位置:首页 > 数据库 > MySQL

MySQL子查询(嵌套查询)

2019-05-10 22:15 162 查看

一个查询语句嵌套在另一个查询语句内部的查询

常用操作符:ANY(SOME), ALL, IN, EXISTS

比较运算符:>, >=, <, <=, != 等

创建两个表,表明分别是tb1,tb2,并向其各插入了数据。

        

 

1.带ANY(SOME)关键字的子查询

这里any和some是同义词,都是表示满足任一条件。

例:查询tb1中的所有数据,只要大于tb2表中数据的任意值,既符合查询条件。

select num1 from tb1 where num1>ANY(select num2 from tb2);

 

2.带ALL关键字的子查询

例:查询tb1中的所有数据,返回其中比tb2表中任何值都大的数据。

select num1 from tb1 where num1>ALL(select num2 from tb2);

 

3.带EXISTS关键字的子查询

例1:查询fruits表中name字段下是否有apple,若有则查询fruits表中的记录,否则不查询。

select * from fruits where EXISTS(select name from fruits where name='apple');

例2:查询tb1表中是否存在num1=13的记录,若存在,则查询fruits表中price大于6.00的记录。

select * from fruits where price>6.00 and EXISTS (select num1 from tb1 where num1=13);

相反,可以使用 not exists 查询不存在的,用法相同。

 

4.带IN关键字的子查询

内层查询语句返回一个数据列,该数据列将提供给外层查询语句进行比较操作。

例如:查询tb1表中的num1字段下的数据作为数据列,fruits表中id字段下的数据与其进行比较,返回符合条件的记录。

select * from fruits where id IN (select num1 from tb1);

 

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

select * from 表名 where 字段名 > (select ······);

 

 

 

 

 

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: