分享

MySQL 子查询语句

 Fengsq501u81r4 2021-08-01

子查询基本概念

子查询,是指以结果集的形式供其他查询语句使用的查询语句。这样,可以在一个完整的查询语句之中,嵌套了若干个不同功能的小查询,从而一起完成更为复杂的查询。

根据结果集的类型不同,子查询大致可以分为如下四类:

  • 单行单列子查询;
  • 单行多列子查询;
  • 多行单列子查询;
  • 多行多列子查询。

单行单列子查询

位置:select子句、where子句等可以使用一个常规值的任意子句。

select子句

功能:结果集作为一个常规值,参与字段列计算。

select ename, sal, (select avg(sal) from emp) as avg, (sal-(select avg(sal) from emp)) as balancefrom emp;

where子句

功能:结果集作为一个常规值,参与查询条件计算(算数 逻辑)。

select        ename,         sal, from        empwhere        sal > (select avg(sal) from emp);

单行多列子查询

位置:where子句。

功能:结果集作为一个复合值,参与查询条件的多个字段的判等计算。

select *from emp ewhere (e.job, e.sal) = (select job, sal from emp where ename='scott' );

多行单列子查询

位置:where子句。

功能:结果集作为一个集合值,参与查询条件的集合运算。

# in 集合运算符:必须在集合中。select        *from        empwhere        sal in (select min(sal) from emp group by deptno);
# any 集合运算符:可以不在集合中,满足任意一个比较条件。select *from empwhere sal > any(select min(sal) from emp where job='manager' group by deptno);
# all 集合运算符:可以不在集合中,必须满足所有比较条件;select        *from        empwhere        sal <> all(select min(sal) from emp where job='manager' group by deptno);
# exists 集合运算符:只检测结果集是否为空,不比较其中的元素。select *from emp ewhere exists(select * from emp);

多行多列子查询

位置:from子句。

from子句

功能:结果集作为一个临时表,进行二次查询、多表连接等运算。

# 作为临时表进行二次查询;select        *from        (select * from emp where comm is null) as emp where        job='manager';
# 作为临时表进行多表连接;select e.*, d.dname, d.loc from emp e right join (select * from dept) d on e.deptno=d.deptno;

insert子句

功能:采用【insert...select...】结构,取代【insert...values...】结构,实现从其他数据表导入数据的功能。

insert into         managerselect        *from        empwhere        job='manager';

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约