MYSQL5天速成--第三天

MYSQL5天速成—第三天

子查询介绍
含义:出现在其他语句中的select 语句,称为子查询或者内查询
外部的查询语句称为外查询或主查询
分类 :
按子查询出现的位置分类:
select 后面
from 后面
支持表子查询
having或者where 后面
支持标量子查询
列子查询
行子查询
exists后面(相关子查询)

按结果集的行列数不同
标量子查询(结果集只有一行一列)
列子查询(结果集只有一列多行)
行子查询(结果集有多行多列)
表子查询(结果集一般为多行多列)

where 和having后面
标量子查询 (单行子查询)
列子查询(多行子查询)
行子查询(多列多行)
特点:1.子查询放在小括号内
2.子查询一般放在条件的右侧
3.标量子查询,一般搭配着单行操作符使用 < > >= <= = <>
列子查询一般搭配着多行操作符使用
in any/some all
4.子查询的执行都优先于主查询,主查询的条件用到了子查询的结果

非法使用标量子查询:子查询的结果不是一行一列

谁的工资比AB高

1.查询AB的工资
select  salary 
from employees
where lastname = 'AB';
2.查询员工信息,需要满足1的结果
select *
from employees
where employees.salary >(
		select  salary 
		from employees
		where lastname = 'AB');

返回公司工资最少的员工的lastname job_id salary

1.查询公司中最少工资
select  min(salary)
from employees;
2.select  lastname ,job_id,salary
from employees
where salary = (
	select  min(salary)
	from employees);

查询最低工资大于50号部门的最低工资的部门id和最低工资

1.查询50号部门的工资
select salary
from departments
where department_id = 50
2.查询每个部门的最低工资
select department_id,min(salary)
from employees;
group by department_id;

3.2的基础上筛选1
select department_id,min(select)
from departments
group by department_id
having min(salary)>(
	select salary
	from departments
	where department_id = 50);

列子查询
多行子查询:返回多行、使用多行比较符

操作符 含义
in / not in 等于列表中的任意一个
any / some 和子查询返回的某一个值比较
all 和子查询返回的所有值进行比较

返回local_id中1400或者1700部门中所有的员工姓名

1.select department_id
from departments
where local_id in (1400,1700);

2.select lastname
from employees
where department_id in (
select department_id
from departments
where local_id in (1400,1700));

行子查询
结果集一行多列或者多行多列
查询员工编号最小工资最高的员工信息

select *
from employees
where(employ_id,salary)=
(select min(employ_id),max(salsry)
from employees);

放在select的后面
每个部门的员工个数

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

查询员工号为102的员工名

select lastname
from employees
where employ_id in(
	select employ_id
	from employ
	where local_id = 102);

from后面
将子查询充当一张表,要求起别名
查询每个部门的平均工资的工作等级

select  avg(salary),department_id
from employees
group by department_id

select * from job_grade

2.进行连接
select avg.*,g.grade_level
from (
	select  avg(salary) ag,department_id
	from employees
	group by department_id
) avg inner join job_grade j
on avg.ag between max(salary) and min(salary);

exists后面相关子查询

select  exists (select employees_id from employees);

语法:exists(完整查询语句)
结果 :只有1或者0
查询有员工的部门名

select department_name
from department d
where exists(
	select *
	from employees e
	where d.department_id = e.department_id);

你可能感兴趣的:(mysql)