MySQL 查询语句--------------进阶7:子查询

#进阶7:子查询
/*
含义: 出现在其他语句中的select语句,称为子查询或者内查询

	外部的查询语句,称为主查询或外查询
分类:
按照子查询出现的位置:
	select后面:只支持标量子查询
	from后面:支持表子查询
	重点:where或者having后面:
		标量子查询,重点
		列子查询,重点
		行子查询(用的较少)
	exists后面(相关子查询):表子查询
按照结果集的行列不同:
	标量子查询(结果集中只有一行一列)
	列子查询(结果集只有一列多行)
	行子查询(结果集为一行多列)
	表子查询(结果集为多行多列)
*/

#一、where或者having后面
/*
1.标量子查询(单行子查询)
2.列子查询(一列多行)
特点:
(1)子查询放在小括号内
(2)子查询一般放在条件的右侧
(3)标量子查询,一般搭配着单行操作符使用
>,<,=,!=,<>

列子查询,一般搭配着多行操作符使用
in/not in,any/some等价于min(),all等价max()
*/

#1.标量子查询
#案例1: 谁的工资比Abel高
#(1)先查询Abel的工资
select salary from employees where last_name="Abel";
#(2)再查询员工的工资,且结果大于Abel的工资
select * from employees where salary>(select salary from employees where last_name="Abel");


#案例2:返回job_id与141号员工相同的,salary比143号多的员工姓名、job_id和工资
(1)查询141号员工的job_id
select job_id from employees where employee_id="141";
(2)查找143号的工资
select salary from employees where employee_id="143";
(3)查找salary比143号多的员工姓名、job_id和工资
select last_name,job_id,salary from employees where salary>(select salary from employees where employee_id="143");
(4)返回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");

#2.列子查询
#案例1:返回location_id是1400或者1700的部门中的所有员工姓名
(1)location_id是1400或者1700的部门
select distinct department_id from departments where location_id=1400 or location_id=1700;
(2)(1)部门中的所有员工姓名(使用  in  )
select last_name from employees;
select last_name from employees where employees.department_id in (select distinct department_id from departments where location_id=1400 or location_id=1700);

#3.行子查询(了解即可)


#二、select 后面
#案例1:查询每个部门的员工个数
/*
(1)先对部门去重
select distinct department_id from employees where department_id is not null;

(2)再查询每个部门的员工个数
select count(employee_id) from employees
select count(employee_id),department_id from employees group by (select distinct department_id from employees where department_id is not null);
*/  思路不对

正确解:
select d.*,(select count(*) from employees e where d.department_id=e.department_id) 个数 from departments d;

#案例2:查询员工号=102的部门名字
select department_id from employees where employee_id=102;
select department_name from departments where department_id=(select department_id from employees where employee_id=102);


#三、from后面

#四、exists后面(相关子查询)
/*
exists是否存在,布尔值
语法:exists(完整的查询语句)
结果:1,或 0
*/
案例1:查询有员工的部门名
select department_name from departments d where exists(select * from employees e where d.department_id=e.department_id);

  

你可能感兴趣的:(MySQL 查询语句--------------进阶7:子查询)