MySQL——子查询

什么是子查询

  • 在一个查询之中嵌套了其他的若干查询
  • 在where查询条件中是一个不确定的值,而是一个来自另一个查询的结果。
  • 语句

ex:查询大于公司平均工资的员工姓名:

select avg(sal) from emp;   /* avg(sal)=2000 */
select * from emp where sal >= 2000;
/* 将上面的语句合并 */
select * from emp where sal >= (select avg(sal) from emp);

ex:查询出工资比anthony还要高的全部雇员信息:

select sal from emp where name='anthony'; /* anthony的工资为10000 */
select * from emp where sal >= 10000;
/* 将上面的语句合并 */
select * from emp where sal >= (select sal from emp where name='anthony');  

注意事项

  • 子查询要用括号括起来
  • 将子查询放在运算符的右边(增加可读性)
  • 对单行子查询使用单行运算符
  • 对多行子查询使用多行运算符

子查询的分类

根据子查询的结果来划分的

单行单列子查询

  • 返回查询结果包含一行数据,看作是一个值,使用在where之后
  • 使用单行记录比较运算符:=; >; <; <=;>=;<>

多行单列子查询

  • 返回查询结果可能多行或者零行,看作是多个值,使用在where之后
  • 使用多行比较运算符:

IN

与返回列表中的任意一个值相等
ex:查询工资等于部门经理的员工信息

select sal from emp where job ='manager';  /* 先查询部门经理的工资 */

《MySQL——子查询》

ANY

与返回的任意一个值比较

  • =ANY:此时和in操作一样
  • >ANY:大于子查询中最小的值
  • <ANY:小于子查询中最大的值

ALL

与返回的值每一个值比较

  • >ALL:大于查询中最大的值
  • <ALL:小于查询中最小的值

多列子查询

  • 返回查询结果的结构是单行或多行,看作是一张临时表,使用在from之后
  • 性能:笛卡尔积的数量
select d.deptno,d.dname,temp.c,temp.a
from dept d join 
 (select deptno,count(empno) c,avg(sal) a from emp group by deptno) temp        
on using(deptno);  

union/union all

join用于把表横向连接,union/union all用于把表纵向连接
注意:

  • union内部的select语句必须拥有相同数量的列

-列也必须拥有兼容的数据类型

  • 每条select语句中的列的顺序必须相同
  • union结果集中的列名总是等于union中第一个select语句中的列名
  • union操作符选取不同的值,如果允许重复的值,使用union all(性能高)
select empno,ename,dname from emp left join dept using(deptno)
union 
select empno,ename,dname from emp right join dept using(deptno);
    原文作者:AnthonyYMH
    原文地址: https://segmentfault.com/a/1190000019231250
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞