子查询

### 1\. 子查询的概念


##### 1.1 子查询的概念和理解


某些查询逻辑中,需要引入另一个查询做为条件或者数据来源进行辅助。

比如:查询与‘TOM’在同一部门工作的其他员工


```

select * from emp where deptno = TOM的deptno and

ename <> 'TOM';


```


TOM的deptno


```

select deptno from emp where ename = 'TOM';


```


将两个独立的查询合并起来


```

select * from emp

where deptno = (select deptno from emp

where ename = 'TOM')

and ename <> 'TOM';


```


整个外部这部分SQL语句被称为外部查询(主查询),括号内查询TOM部门号的这个SQL语句被称为子查询


![image](//upload-images.jianshu.io/upload_images/15606715-7f59de199e141853.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/579/format/webp)


##### 1.2 子查询使用位置


子查询可以使用在很多子句中


*  from子句中,from子句中的子查询可以理解为是一张临时的“表”(视图)

*  where子句中

*  having子句中

    通常主要使用在where和from中


### 2\. 简单子查询(单行子查询)


**单行子查询的查询结果是一行一列的数据**

可以使用常规的> ,<, >=, <=, =, !=进行子查询数据的比较

可以将子查询理解为就是一个简单的数据

示例1:查询比TOM月薪高的员工信息


```

select * from emp where sal > (select

sal from emp where ename = 'TOM')


```


![image](//upload-images.jianshu.io/upload_images/15606715-d95e5201e43012f4.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/568/format/webp)


示例2:查询与LEE是同一职位同一部门的其他员工信息


```

select *

from emp

where job = (select job from emp where

ename = 'LEE')

and deptno = (select deptno from emp where

ename = 'LEE')

and ename <> 'LEE'


```


![image](//upload-images.jianshu.io/upload_images/15606715-c4c26cc14031ce13.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/572/format/webp)


**子查询中可以嵌套其他的子查询,层数限制在32层内**

示例3:查询月薪高于AMY所在部门平均月薪的员工信息


```

select *

from emp

where sal > (select AVG(sal) from emp

        where deptno = (select deptno from emp where ename = 'AMY'))


```


![image](//upload-images.jianshu.io/upload_images/15606715-e44b598a58799cf4.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/580/format/webp)


### 3\. 多行子查询


##### 3.1 多行子查询


**多行子查询返回的是多行一列的数据**

当子查询返回多行记录时,使用=这类的比较运算符无法执行


![image](//upload-images.jianshu.io/upload_images/15606715-aa3a7c5ae957c27b.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/764/format/webp)


当有多条记录返回时,使用IN来进行比较,相当于等于子查询中某个值即可

示例4:查询是经理的员工信息(=)


```

select *

from emp

where empno in (select distinct mgr from

emp where mgr is not null)


```


![image](//upload-images.jianshu.io/upload_images/15606715-3bc5ecc84a947548.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/573/format/webp)


示例5:查询不是经理的员工信息(!=)


```

select *

from emp

where empno not in (select distinct mgr

from emp where mgr is not null)


```


![image](//upload-images.jianshu.io/upload_images/15606715-284d3ad1a1ce336e.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/577/format/webp)


**not in中的数据不能有null值,如果有null值,相当于执行了=null操作,不能筛选出任何数据**


##### 3.2 ANY(SOME)与ALL


主要使用在多行子查询中进行>或<与操作时

ANY(SOME):任何一个

ALL:所有


> ANY 比最小的大

> ALL 比最大的大

> < ANY 比最大的小

> < ALL 比最小的小


![image](//upload-images.jianshu.io/upload_images/15606715-c36b78957b6f97b0.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/917/format/webp)


示例6:查询比10部门所有人月薪都要高的员工信息


```

select *

from emp

where sal > ALL(select sal from emp

where deptno = 10)


```


也可以使用


```

select *

from emp

where sal > (select MAX(sal) from emp

where deptno = 10)


```


![image](//upload-images.jianshu.io/upload_images/15606715-bdda039cfb58dbb8.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/572/format/webp)


使用ANY和ALL执行效率要高于分组函数


##### 3.3 from子句中的子查询


将子查询运用在from中,相当于一张“表”

**必须为作为“表”的子查询起“表别名”(示例7中的t)**

示例7:查询部门编号,部门名称,部门loc,部门人数


```

select

d.deptno,d.dname,d.loc,IFNULL(t.empnum,0)

from dept d left join

   (select deptno, COUNT(empno) as empnum

   from emp

   where deptno is not null

   group by deptno) t

    on(d.deptno = t.deptno)


```


![image](//upload-images.jianshu.io/upload_images/15606715-4cbc9c71f321e8e8.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/386/format/webp)


**在MySQL中,update语句分组函数的结果不能作为子查询的返回结果**


```

update emp set sal = sal + 200

where sal < (select avg(sal) from emp);


```


MySQL中认为更新和子查询不能同时进行。

解决办法:将子查询再次进行嵌套,制作成From中的子查询


```

update emp set sal = sal + 200

where sal < (select asal from(select

avg(sal) from emp) t);


```


### 4\. 相关子查询(难点)


前3节的子查询都属于**独立子查询**,子查询可以独立执行

相关子查询:子查询不可独立执行,必须依赖外部查询


##### 4.1 常规的相关子查询


示例8:查询比自己所在部门平均月薪高的员工信息

常规写法


```

select * from emp e

     join (select deptno, AVG(sal) as asal

       from emp

       group by deptno) t

     on(e.deptno = t.deptno)

where e.sal > t.asal


```


相关子查询写法


```

select * from emp e1

where e1.sal > (select AVG(sal) from emp

e2 where e2.deptno = e1.deptno)


```


![image](//upload-images.jianshu.io/upload_images/15606715-3e30a28848449114.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/581/format/webp)


**相关子查询的特点:外部查询执行一行数据,子查询执行一次**


![image](//upload-images.jianshu.io/upload_images/15606715-717174155c2451b4.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1000/format/webp)


##### 4.2 EXIST关键字


子查询用于验证外部查询的一行记录是否符合子查询的条件

示例9:查询是经理的员工的员工信息


```

select *

from emp e1

where exists (select empno from emp e2

where e2.mgr = e1.empno)


```


![image](//upload-images.jianshu.io/upload_images/15606715-c69f450311213bf4.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/571/format/webp)


![image](//upload-images.jianshu.io/upload_images/15606715-e16fb232a57dbaa4.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1000/format/webp)


如果想表述不存在的逻辑,使用NOT EXISTS

C���P

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 219,039评论 6 508
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,426评论 3 395
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 165,417评论 0 356
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,868评论 1 295
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,892评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,692评论 1 305
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,416评论 3 419
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,326评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,782评论 1 316
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,957评论 3 337
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,102评论 1 350
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,790评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,442评论 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,996评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,113评论 1 272
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,332评论 3 373
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,044评论 2 355

推荐阅读更多精彩内容

  • ### 1\. 笛卡尔积(交叉连接) 笛卡尔积是关系型数据库,进行多表查询的基础 A{a,b,c} B{d,e,f...
    lbon阅读 245评论 0 0
  • 一、使用子查询 语法格式 SELECT select_listFROM tableWHERE expr opera...
    辽A丶孙悟空阅读 2,871评论 0 43
  • 引出 •请思考如下问题? –查询所有员工的每个月工资总和,平均工资? –查询工资最高和最低的工资是多少? –查询公...
    C_cole阅读 7,292评论 0 3
  • 回到了赣州。南方的天气很热,热的使人烦躁不安,夜晚都难以入睡;东北的夏天也热,但是我能够睡得舒适、踏实…我突然想回...
    烨挽清风阅读 231评论 0 0
  • 今天对学生发火了,我很后悔。无论家教还是在上课,许多次都会发生这种情况:我讲了许多次的知识点,讲了多次的题,...
    nlx阅读 344评论 2 2