MySQL子查询

1 子查询[重点,难点]

1.1 基本格式

select fieldName
from tbName
where (子查询结果);

1.2 子查询结果作为条件判断约束

-- 查询工资高于Jack的员工id和姓名
-- 1. 找出Jack的工资
-- 2. 得到Jack工资,作为条件查询对应的员工信息
select salary
from t_employees
where first_name = 'Jack';

select employee_id, first_name
from t_employees
where salary > 8400;

-- 整合为子查询
-- 条件判断
select employee_id, first_name
from t_employees
where salary > (select salary
                from t_employees
                where first_name = 'Jack');

1.3 子查询结果作为枚举限制 in

-- 查询和Jack同部门的员工信息
-- 1. 找出Jack的部门编号
select department_id
from t_employees
where first_name = 'Jack';

-- 2. 根据Jack的部门编号,使用in枚举查询,限制条件
select employee_id, first_name
from t_employees
where department_id in (80);

-- 整合为子查询
select employee_id, first_name
from t_employees
where department_id in (select department_id
                        from t_employees
                        where first_name = 'Jack');

1.4 子查询结果作为一张表,从表内查询指定数据

-- 查询员工表中工资前五名的员工信息
-- 1. 找到员工的id,first_name,工资降序
select employee_id, first_name
from t_employees
order by salary desc;

select employee_id, first_name
from (select employee_id, first_name
      from t_employees
      order by salary desc) as temp
limit 5;

1.5 合并查询[仅了解]

union

-- 合并,要求查询要求的字段个数一致
-- 去重
select employee_id, first_name
from t_employees
union
select job_id, job_title
from t_jobs;

-- 合并,要求查询要求的字段个数一致
-- 不去重
select department_id, first_name
from t_employees
union all
select manager_id, department_name
from t_departments;
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 10
    评论
评论 10
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值