MySQL子查询介绍和where后的标量子查询

子查询介绍

出现在其他语句中的select语句,被包裹的select语句就是子查询或内查询

包裹子查询的外部的查询语句:称主查询语句

sql 复制代码
select last_name from employees
where department_id in(
select department_id from departments
where location_id=1700
);

子查询分类

通过位置来分

select 后面:仅仅支持标量子查询

from 后面:支持表子查询

where 或having 后面:支持标量子查询(重要)\列子查询(重要)\行子查询(用的较少)

exists 后面(相关查询):支持表子查询

按结果集的行列数不同分类

标量子查询(结果集只有一行一列)

列子查询(结果集只有一列但有多行)

行子查询(结果集只有一行但有多列)

表子查询(结果集多行多列)

子查询特点

子查询放在小括号内

子查询一般放在条件的右侧

标量子查询,一般搭配着单行操作符来使用(> < >= =)

列子查询,一般搭配着多行操作符使用:in any/some all

子查询的执行顺序优先于主查询(select后的子查询存在例外)

案例

1.where后面的标量子查询

案例:查询工资比Abel这个人的高的员工信息

sql 复制代码
select * from employees
where salary>(
select
salary
from employees
where last_name='Abel'
);

2.查询job_id与141号员工相同,salary比143号员工多的员工姓名,job_id和工资

sql 复制代码
select last_name,job_id,salary
from employees
where job_id=(select job_id from employees
where employee_id=142 ) and salary>(select salary
from employees where employee_id=143);
(这个案例说明一个主查询里可以放很多个子查询)

3.子查询里用到分组函数:查询公司工资最少的员工的last_name,job_id和salary

sql 复制代码
select last_name,job_id,salary from employees
where salary=(select min(salary) from employees);

4.用到having的子查询:查询最低工资大于50号部门最低工资的部门id和其最低工资

sql 复制代码
select department_id , min(salary) from employees
group by department_id
having min(salary)>(select min(salary) from employees where department_id=50);
相关推荐
房开民几秒前
PyQt5 常用模块(对应Qt五大模块)
数据库·pyqt
QYRdata8 分钟前
Oracle云应用咨询服务驶入增长快车道:2026-2032年复合增长率达8.5%
数据库·oracle
AI办公探索者19 分钟前
多租户架构下数据隔离的三种实现方案对比
数据库·ai·oracle·架构
2601_9632827727 分钟前
寒地专网通信实战:对讲机技术选型、组网优化与东北多行业落地全指南
大数据·数据库·人工智能
霖霖总总34 分钟前
[MongoDB小技巧29]MongoDB PITR 深度工程化:从全量备份到“任意时间点”精准回滚
数据库·mongodb
JckOLF04Z1 小时前
自动开机调用迅雷下载数据库备份,完成后自动关机
数据库·单片机·嵌入式硬件
霖霖总总1 小时前
[MongoDB小技巧30]MongoDB 数据生命周期管理完全指南:从 TTL 索引到冷热分离归档
数据库·mongodb
生戎马 平安京策1 小时前
SQL Transcation的一些总结
数据库·sql·oracle
吃饱了得干活1 小时前
向量数据库 Milvus:从零搭建 RAG 向量数据库实战
数据库·langchain·agent
jjjava2.01 小时前
MyBatis动态if/trim/where/set标签详解
java·开发语言·数据库