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);
相关推荐
海南java第二人8 小时前
Nebula Graph 实战:基于图数据库存储 CMDB 实体关系
数据库·图数据库·nebula
曹牧9 小时前
oracle:“not all variables bound”
数据库·oracle
数据库百宝箱9 小时前
Oracle RMAN Image Copy 本地恢复
数据库·oracle
zuYM4g7Dp10 小时前
NoSql数据库设计心得
数据库·nosql
bjzhang7511 小时前
CentOS下安装MySQL详解
linux·mysql·centos
睡不醒男孩03082312 小时前
第七篇:揭秘 PostgreSQL 数据库内核级管控:CLup 深度架构设计与高可用底座技术白皮书
数据库·postgresql·clup
cmes_love12 小时前
Level 2逐笔成交历史数据下载方法笔记
数据库·笔记·oracle
swordbob13 小时前
MySQL字符集陷阱:从Oracle迁移踩坑到utf8mb4强制规范
数据库·sql
牛油果子哥q13 小时前
【C++ STL string 】C++ STL string 终极精讲:底层原理、内存机制、全套API、深浅拷贝、易错坑点与工程实战规范
数据库·c++
十五年专注C++开发13 小时前
MySql中各种功能用sql语句实现总结
数据库·sql·mysql