Skip to content
目录概览

子查询常用的情况有哪些?

  1. 子查询是单行单列的情况: 结果集是一个值,父查询使用:=、 <、 > 等运算符

    sql
    -- 查询工资最高的员工是谁? 
    select  * from employee where salary=(select max(salary) from employee);   
    
    1
    2
  2. 子查询是多行单列的情况: 结果集类似于一个数组,父查询使用:in 运算符

    sql
    -- 查询工资最高的员工是谁? 
    select  * from employee where salary=(select max(salary) from employee);
    
    1
    2
  3. 子查询是多行多列的情况: 结果集类似于一张虚拟表,不能用于where条件,用于select子句中做为子表

    sql
    -- 1) 查询出2011年以后入职的员工信息
    -- 2) 查询所有的部门信息,与上面的虚拟表中的信息比对,找出所有部门ID相等的员工。
    select * from dept d,  (select * from employee where join_date > '2011-1-1') e where e.dept_id =  d.id;    
    
    -- 使用表连接:
    select d.*, e.* from  dept d inner join employee e on d.id = e.dept_id where e.join_date >  '2011-1-1'
    
    1
    2
    3
    4
    5
    6