子查询:类型、语法、和注意事项
使用子查询能解决哪些问题?
子查询语法:
select select_list from table where expr operator (select select_list from table);
子查询(内查询)在主查询(外查询)之前执行。
主查询使用子查询结果。
位置:select,where,from,having
1、查询谁的工资比Abel高
select last_name, salary from employees
where salary>
(select salary
from employees
where last_name='Abel');
子查询要包含在括号内。
将子查询放在比较条件的右侧增强可读性(子查询可以出现在比较运算符的两侧)
单行操作符对应单行子查询,多行操作符对应多行子查询
– 子查询中的组函数
– HAVING 子句中的子查询
只返回一行
使用单行比较操作符
select last_name, job_id, salary from employees
where job_id in (select job_id from employees
where last_name like 'Taylor')
and salary in
(select salary
from employees
where last_name like 'Taylor');
在子查询中使用组函数
select last_name, job_id, salary from employees where
salary=(select min(salary) from employees);
首先执行子查询
向主查询中的 HAVING 子句返回结果
select department_id, min(salary)
from employees
group by department_id
having min(salary)>
(select min(salary)
from employees
where department_id=50);
多行子查询使用单行比较符,以下为错误写法
子查询中的空值问题
select last_name, job_id from employees
where job_id=
(select job_id from employees
where last_name='haas');
多行子查询
– 使用 ALL 或 ANY
返回多行。
使用多行比较操作符。
在多行子查询中使用 ANY
select employee_id, last_name, job_id, salary
from employees where salary <任何
(选择工资从员工
job_id=IT_PROG)
job_id & lt;比;“IT_PROG”;
在多行子查询中使用所有,操作符
选择employee_id last_name、job_id,从员工工资
工资& lt;所有的
(选择工资从员工
job_id=IT_PROG)
job_id & lt;比;“IT_PROG”;
子查询中的空值
选择emp.last_name
从员工emp
emp.employee_id不是在
(选择下。manager_id
从员工经理);
1,人力资源部部门的同事想要你帮忙写一个SQL语句,该SQL语句可以传入一个值(员工的last_name),然后返回结果是该员工同一部门同事的last_name和hire_date,且要求该员工不在返回结果中。
举个例子,如果用户输入“Zlotkey”,结果就会返回除了Zlotkey之外的同一部门的其他同事的