1、查找比Abel工资高的员工
#方式一:SELECT salary
FROM employees
WHERE last_name ='Abel';SELECT last_name, salary
FROM employees
WHERE salary >11000;#方式二:自连接SELECT e2.last_name, e2.salary
FROM employees e1, employees e2
WHERE e1.last_name ='Abel'AND e1.salary < e2.salary;#方式三:子查询SELECT last_name,salary
FROM employees
WHERE salary >(SELECT salary
FROM employees
WHERE last_name ='Abel');
题目中子查询和自连接方式对比,自连接效率更高。
子查询实际上是通过未知表进行查询后的条件判断。
自连接是通过已知的自身数据表进行条件判断,因此在大部分 DBMS 中都对自连接处理进行了优化。
2、 单行子查询
2.1、单行比较查询
单行比较操作符 >=>=<=<<>
1、题目:查询工资大于149号员工工资的员工的信息
SELECT last_name, salary
FROM employees
WHERE salary >(SELECT salary
FROM employees
WHERE employee_id =149);2、题目:返回job_id与141号员工相同,salary比143号员工多的员工姓名,job_id和工资
SELECT last_name, job_id, salary
FROM employees
WHERE job_id =(SELECT job_id
FROM employees
WHERE employee_id =141)AND salary >(SELECT salary
FROM employees
WHERE employee_id =143);3、题目:返回公司工资最少的员工的last_name,job_id和salary
SELECT last_name, job_id, salary
FROM employees
WHERE salary =(SELECTMIN(salary)FROM employees);4、查询与141号或174号员工的manager_id和department_id相同的其他员工的employee_id,manager_id,department_id
# 实现方式1:不成对比较SELECT employee_id, manager_id, department_id
FROM employees
WHERE manager_id IN(SELECT manager_id
FROM employees
WHERE employee_id IN(174,141))AND department_id IN(SELECT department_id
FROM employees
WHERE employee_id IN(174,141))AND employee_id NOTIN(174,141);# 实现方式2:成对比较SELECT employee_id, manager_id, department_id
FROM employees
WHERE(manager_id, department_id)IN(SELECT manager_id, department_id
FROM employees
WHERE employee_id IN(141,174))AND employee_id NOTIN(141,174);
3、题目:查询员工的id,salary,按照department_name 排序
SELECT employee_id, salary
FROM employees e
ORDERBY(SELECT department_name
FROM departments d
WHERE e.department_id = d.department_id
);4、题目:若employees表中employee_id与job_history表中employee_id相同的数目不小于2,输出这些相同id的员工的employee_id,last_name和其job_id
SELECT e.employee_id, e.last_name, e.job_id
FROM employees e
WHERE2<=(SELECTCOUNT(*)FROM job_history
WHERE employee_id = e.employee_id);
5、EXISTS 与 NOT EXISTS关键字
关联子查询通常也会和 EXISTS操作符一起来使用,用来检查在子查询中是否存在满足条件的行。
如果在子查询中不存在满足条件的行:条件返回 FALSE,继续在子查询中查找。
如果在子查询中存在满足条件的行:条件返回 TRUE,不再子查询中继续查找。
NOT EXISTS关键字表示如果不存在某种条件,则返回TRUE,否则返回FALSE。
1、题目:查询公司管理者的employee_id,last_name,job_id,department_id信息
# 方式一:SELECT employee_id, last_name, job_id, department_id
FROM employees e1
WHEREEXISTS(SELECT*FROM employees e2
WHERE e2.manager_id = e1.manager_id);# 方式二:自连接SELECTDISTINCT e1.employee_id, e1.last_name, e1.job_id, e1.department_id
FROM employees e1 JOIN employees e2
WHERE e1.employee_id = e2.employee_id;# 方式三:SELECT employee_id, last_name, job_id, department_id
FROM employees
WHERE employee_id IN(SELECTDISTINCT manager_id
FROM employees);2、题目:查询departments表中,不存在于employees表中的部门的department_id和department_name
SELECT department_id, department_name
FROM departments d
WHERENOTEXISTS(SELECT*FROM employees
WHERE department_id = d.department_id);