当前位置:   article > 正文

MySQL where后面的列子查询使用_where后面的条件在列表中

where后面的条件在列表中

多行子查询

  • 返回多行
  • 使用多行操作比较操作符
操作符含义
IN/NOT IN等于列表中 任意一个
ANY/SOME和子查询返回的 某一个值 比较
ALL+和子查询返回的 所有值 比较

#案例1:返回location_id是1400或1700的部门中的所有员工姓名

#①查询location_id是1400或1700的部门编号

  1. SELECT DISTINCT department_id
  2. FROM departments
  3. WHERE location_id IN(1400,1700)

#②查询员工姓名,要求部门号是①列表中的某一个

  1. SELECT last_name
  2. FROM employees
  3. WHERE department_id in(
  4. SELECT DISTINCT department_id
  5. FROM departments
  6.   WHERE location_id IN(1400,1700)
  7. );

#或​​​​​​​

  1. SELECT last_name
  2. FROM employees
  3. WHERE department_id = ANY(
  4. SELECT DISTINCT department_id
  5. FROM departments
  6. WHERE location_id IN(1400,1700)
  7. );

注意:not in 等价于 <> ALL​​​​​​​

  1. SELECT last_name
  2. FROM employees
  3. WHERE department_id not in(
  4. SELECT DISTINCT department_id
  5. FROM departments
  6. WHERE location_id IN(1400,1700)
  7. );

等价于​​​​​​​

  1. SELECT last_name
  2. FROM employees
  3. WHERE department_i <> ALL(
  4. SELECT DISTINCT department_id
  5. FROM departments
  6. WHERE location_id IN(1400,1700)
  7. );

#案例2:返回其它工种中比job_id为‘IT_PROG’工种任一工资低的员工的员工号、姓名、job_id 以及salary

#①查询job_id为‘IT_PROG’部门任一工资​​​​​​​

  1. SELECT DISTINCT salary
  2. FROM employees
  3. WHERE job_id = 'IT_PROG'

#②查询员工号、姓名、job_id 以及salary,salary<(①)的任意一个​​​​​​​

  1. SELECT last_name,employee_id,job_id,salary
  2. FROM employees
  3. WHERE salary<ANY(
  4. SELECT DISTINCT salary
  5. FROM employees
  6.   WHERE job_id = 'IT_PROG'
  7. ) AND job_id<>'IT_PROG';

#或​​​​​​​

  1. SELECT last_name,employee_id,job_id,salary
  2. FROM employees
  3. WHERE salary<(
  4. SELECT MAX(salary)
  5. FROM employees
  6.   WHERE job_id = 'IT_PROG'
  7. ) AND job_id<>'IT_PROG';

#案例3:返回其它部门中比job_id为‘IT_PROG’部门所有工资都低的员工   的员工号、姓名、job_id 以及salary​​​​​​​

  1. SELECT last_name,employee_id,job_id,salary
  2. FROM employees
  3. WHERE salary<ALL(
  4. SELECT DISTINCT salary
  5. FROM employees
  6.   WHERE job_id = 'IT_PROG'
  7. ) AND job_id<>'IT_PROG';

#或​​​​​​​

  1. SELECT last_name,employee_id,job_id,salary
  2. FROM employees
  3. WHERE salary<(
  4. SELECT MIN( salary)
  5. FROM employees
  6.   WHERE job_id = 'IT_PROG'
  7. ) AND job_id<>'IT_PROG';

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/菜鸟追梦旅行/article/detail/384814
推荐阅读
相关标签
  

闽ICP备14008679号