MySQL——子查询

栏目: 数据库 · 发布时间: 7年前

内容简介:ex:查询大于公司平均工资的员工姓名:ex:查询出工资比anthony还要高的全部雇员信息:根据子查询的结果来划分的

什么是子查询

  • 在一个查询之中嵌套了其他的若干查询
  • 在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';  /* 先查询部门经理的工资 */

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);

以上所述就是小编给大家介绍的《MySQL——子查询》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Programming Collective Intelligence

Programming Collective Intelligence

Toby Segaran / O'Reilly Media / 2007-8-26 / USD 39.99

Want to tap the power behind search rankings, product recommendations, social bookmarking, and online matchmaking? This fascinating book demonstrates how you can build Web 2.0 applications to mine the......一起来看看 《Programming Collective Intelligence》 这本书的介绍吧!

HEX CMYK 转换工具
HEX CMYK 转换工具

HEX CMYK 互转工具

HEX HSV 转换工具
HEX HSV 转换工具

HEX HSV 互换工具

HSV CMYK 转换工具
HSV CMYK 转换工具

HSV CMYK互换工具