单行比较操作符

操作符 含义
= equal to
> greater than
>= greater than or equal to
< less than
<= less than or equal to
<> not equal to

代码示例

题目:查询工资大于 149 号员工工资的员工的信息
image-20210914232952626.png
题目:返回 job_id 与 141 号员工相同,salary 比 143 号员工多的员工姓名,job_id 和工资

  1. SELECT last_name, job_id, salary
  2. FROM employees
  3. WHERE job_id =
  4. (SELECT job_id
  5. FROM employees
  6. WHERE employee_id = 141)
  7. AND salary >
  8. (SELECT salary
  9. FROM employees
  10. WHERE employee_id = 143);

题目:返回公司工资最少的员工的 last_name,job_id 和 salary

  1. SELECT last_name, job_id, salary
  2. FROM employees
  3. WHERE salary =
  4. (SELECT MIN(salary)
  5. FROM employees);

题目:查询与 141 号或 174 号员工的 manager_id 和 department_id 相同的其他员工的employee_id,manager_id,department_id

实现方式 1:不成对比较

  1. SELECT employee_id, manager_id, department_id
  2. FROM employees
  3. WHERE manager_id IN
  4. (SELECT manager_id
  5. FROM employees
  6. WHERE employee_id IN (174,141))
  7. AND department_id IN
  8. (SELECT department_id
  9. FROM employees
  10. WHERE employee_id IN (174,141))
  11. AND employee_id NOT IN(174,141);

实现方式 2:成对比较

  1. SELECT employee_id, manager_id, department_id
  2. FROM employees
  3. WHERE (manager_id, department_id) IN
  4. (SELECT manager_id, department_id
  5. FROM employees
  6. WHERE employee_id IN (141,174))
  7. AND employee_id NOT IN (141,174);

HAVING 中的子查询

  • 首先执行子查询。
  • 向主查询中的HAVING 子句返回结果。

题目:查询最低工资大于50号部门最低工资的部门id和其最低工资

  1. SELECT department_id, MIN(salary)
  2. FROM employees
  3. GROUP BY department_id
  4. HAVING MIN(salary) >
  5. (SELECT MIN(salary)
  6. FROM employees
  7. WHERE department_id = 50);

CASE 中的子查询

在CASE表达式中使用单列子查询:

题目:显式员工的 employee_id,last_name 和 location。其中,若员工 department_id 与 location_id 为 1800 的 department_id 相同,则 location 为“Canada”,其余则为“USA”。

  1. SELECT employee_id, last_name,
  2. (CASE department_id
  3. WHEN
  4. (SELECT department_id FROM departments
  5. WHERE location_id = 1800)
  6. THEN 'Canada' ELSE 'USA' END) location
  7. FROM employees;

子查询中的空值问题

  1. SELECT last_name, job_id
  2. FROM employees
  3. WHERE job_id =
  4. (SELECT job_id
  5. FROM employees
  6. WHERE last_name = 'Haas');

子查询不返回任何行

非法使用子查询

  1. SELECT employee_id, last_name
  2. FROM employees
  3. WHERE salary =
  4. (SELECT MIN(salary)
  5. FROM employees
  6. GROUP BY department_id);

1554992135819.png多行子查询使用单行比较符