zoukankan      html  css  js  c++  java
  • 子查询

    子查询:在一个查询的内部还包括另一个查询,则此查询称为子查询。

    Sql的任何位置都可以加入子查询。

    范例:查询比部门编号为7698的员工工资高的雇员

    分析:查询出 7698 员工的工资是多少,把它作为条件

    select * from emp t1 where t1.sal >(
    select t.sal from emp t where t.empno=7698)

    结果

    子查询在操作中有三类:

    1、单列子查询:返回的结果是一列的一个内容

    -- 查询出比雇员 7654 的工资高,同时从事和 7788的工作一样的员工
    select * from emp t1 where t1.sal >(
    select t.sal from emp t where t.empno=7654) 
    and t1.job = (select t2.job from emp t2 where t2.empno=7788)

    其中:select t2.job from emp t2 where t2.empno=7788查询的结果为ANALYST

    结果

    2、单行子查询:返回多个列,有可能是一个完整的记录

    3、多行子查询:返回多条记录

    范例:要求查询每个部门的最低工资和最低工资的雇员和部门名称

    -- 使用显示内连接
    select emp.ename,d.dname,a.losal from emp 
    inner join 
    (select t1.deptno,min(t1.sal) as losal from emp t1 group by t1.deptno) a on emp.sal=a.losal
    inner join dept d on d.deptno = a.deptno
    -- 使用隐式内连接
    select emp.ename,d.dname,a.losal from emp,
    (select t1.deptno,min(t1.sal) as losal from emp t1 group by t1.deptno) a,dept d 
    where d.deptno = a.deptno and emp.sal=a.losal

    结果:

     其中:select t1.deptno,min(t1.sal) as losal from emp t1 group by t1.deptno,该子查询查出的结果为

    在返回多条记录的子查询中,可以把它的结果集当做一张表,给起个别名, 如图中的 a。
  • 相关阅读:
    Gitlab邮箱配置
    Zabbix邮件告警提示Couldn't resolve host name解决办法
    Gitlab备份和恢复操作
    Gitlab权限管理
    编译安装Nginx
    [0] 数据库读写分离
    [0] C# & MongoDB
    [0] 平衡二叉树
    [0] 分布式存储 Memcached
    [0] MSSQL 分库查询
  • 原文地址:https://www.cnblogs.com/zwh0910/p/14748123.html
Copyright © 2011-2022 走看看