mysql 子查询和联合查询

子查询

出现在其它语句中的select语句称为子查询或内查询,内部嵌套其它select语句,外部的查询语句,称为主查询或外查询

分类
按子查询出现的位置:

  • select 后面:仅仅支持标量子查询
  • from后面:支持表子查询
  • where 或者 having 后面:标量子查询、列子查询、行子查询
  • exists 后面(相关子查询)表子查询

结果集的行数不同:

  • 标量子查询(结果集只有一行一列)
  • 列子查询(结果集只有一列多行)
  • 行子查询(结果集只有一行多列)
  • 表子查询(结果集一般为多行多列)

一、where 或having后面

1.标量子查询(单行子查询)
2.列子查询(多行子查询)

3.行子查询(多行多列)
特点:
1.子查询放在小括号内
2子查询一般放在条件右侧
3.标量子查询,一般搭配这单行操作符使用 > < >= <= <>
列子查询一般搭配这单行操作符使用
in any/some all
1.标量子查询
查询谁的工资比Abel的工资高
a.查询Abel的工资

select salary from employees where last_name = 'Abel'

select salary from employees 
where salary>
(select salary from employees where last_name = 'Abel');

一个查询中可以放多个子查询
子查询可以放分组函数

查询公司最低工资的员工名,工资,job_id

select salary ,last_name,job_id from employees where salary=(select min(salary) from employees );

多行子查询:一般要搭配操作符(in,not in, any,some, all)
a.返回location_id 是1400或1700的部门编号

select department_id from departments where location_id in(1400,1700);

b.查询员工姓名,要求是上面部门编号列表中的一个(sql 格式)

select last_name 
from employees
 where department_id in (
select department_id
 from departments
  where location_id in(1400,1700));

返回其它工种中 比job_id 为‘IT_PROG’工种任一工资低的员工的工号、姓名、job_id 以及salary
(这个案例的问题有点长,可以把他拆开来做)
a.查询’IT_PROG‘部门的员工的工号姓名job_id salary

select distinct salary 
from employees 
where job_id='IT_PROG';

b.查询员工号、姓名、job_id、salary<上面列表中的任意一个

select last_name,employee_id,job_id,salary
FROM employees 
where salary < any(
select distinct salary 
from employees 
where job_id='IT_PROG'
)and job_id<>'IT_PROG';

3.行子查询(一行多列,多行多列)很少使用
查询()

二、select 后面

案例:查询每个部门员工的个数

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

from 后面

例如:查询每个部门平均工资等级

select ag_dep.*,g.grade_level
from(
select avg(salary) ag,department_id
from employees
GROUP BY department_id
) ag_dep 
inner join job_grades g
on ag_dep.ag BETWEEN lowest_sal and highest_sal;

exists后面(相关子查询)

exists 语法
exists (完整的语句) 结果为1或0;
select exists (select employee_id from employees );

分页查询

语法:
select 查询列表
from 表
(join type join 表2
on 连接条件
where 筛选条件
group by 分组条件
having 筛选条件
order by 排序条## 标题件)
limit 起始索引,size ;
特点:limit 放在查询语句的最后;

显示前5条数据

select * from employees limit 0,5;
select * from employees limit 5;

显示11到25条数据

select * from employees limit 10,15;

联合查询

union 联合 合并:将多条查询语句的结果合并成一个结果
例如:查询部门编号>90 或邮箱包含a的员工信息
union 默认去重,使用union all 可以保留重复项

select * from employees where email like '%a%' or department_id>90;
select * from employees where email like'%a%'
union 
select * from employees where department_id >90;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值