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);
相关推荐
shirsl2 分钟前
数据开发实时项目问题整理
数据库·sql·big data
bbq粉刷匠23 分钟前
数据库设计实践
数据库
java_logo24 分钟前
Docker 部署 ClickHouse Server:轻松搭建列式 OLAP 分析数据库平台
数据库·clickhouse·docker·私有化部署·olap·列式数据库·轩辕镜像
盛世宏博智慧档案35 分钟前
高速 ETC 门架外场机房温湿度远程监测解决方案
服务器·数据库·php·高度·高速·温湿度
—Miss. Z—36 分钟前
计算机三级数据库技术—应用题2️⃣
数据库·mysql
PrudentWoo39 分钟前
PostgreSQL 12 登录失败:role “postgres“ is not permitted to log in 的排查与修复
数据库·postgresql
这个DBA有点耶1 小时前
临时表从4.7秒到0.12秒:不是所有Using temporary都需要优化
数据库·mysql·代码规范
天衍四九-1 小时前
排查慢SQL用explain分析执行计划,主要关注哪些字段?
数据库·sql
Meta391 小时前
PostgreSQL报SELECT rule‘s target entry X has different type from column “XXX“
数据库·postgresql·dubbo
洋不写bug2 小时前
二叉树(四)经典算法题目解析,公共祖先,二叉树构造,非递归遍历
数据库·算法·二叉树·二叉树构造·公共祖先