肖sir__mysql之子查询语句__006

一、子查询

定义:一个查询嵌套另一个查询

例如:

题目:财务部门的收入总和;

dept:财务部门

incoming:工资

(1)先将一个结果查询出来:财务部门的编号查询出来

select dept1 from dept where dept_name="财务";(一个查询)

(2)查询出来的结果作为一个条件,在查询

select sum(incoming) from emp where dept2=(select dept1 from dept where dept_name="财务" )

二、子查询的分类

1、标量子查询(返回一个值)

标量子查询 把一个sql执行返回的一个值,作为另一sql的条件,得到的结果是一行一列,一般出现在where 之后

select dept1 from dept where dept_name="财务";

select sum(incoming) from emp where dept2=(select dept1 from dept where dept_name="财务" )

注意点:

标量子查询允许使用符号: =,>,<,>=,=<,<

2、列子查询(返回一列)

定义:返回的值是一列值,通常在where条件后使用:in ,not in

案例:select dept1 from dept where dept_name="财务" or dept_name="销售" ;

select sum(incoming) from emp where dept2 in (select dept1 from dept where dept_name="财务" or dept_name="销售" )group by dept2 ;

案例:求工资大于5000的部门

select dept2 from emp where incoming>5000;

select dept_name from dept where dept1 in (select dept2 from emp where incoming>5000)

(3)行子查询(返回的是一行多列)

定义:值子查询返回的结果集是一行多列,一般也是在where 后

select incoming,dept2 from emp where name="刘九" ;

select * from emp where (incoming,dept2) =any( select incoming,dept2 from emp where name="刘九" )

(4)表子查询(多行多列)

定义:子查询返回结果是一个表

返回表,一般是在from 后,

select * from dept INNER JOIN emp on dept.dept1=emp.dept2 ;

select name from (

select * from dept INNER JOIN emp on dept.dept1=emp.dept2 ) as s where dept_name="财务" ;

注意:临时表 as 取别名,

别名.incoming

相关推荐
Elastic 中国社区官方博客6 小时前
搜索倍增器:推动收入、生产力和 AI 实现规模化
大数据·数据库·人工智能·elasticsearch·搜索引擎·ai·全文检索
东风破_7 小时前
从输入 juejin.cn 到看到页面:DNS、Nginx、服务器集群与 CDN 到底在做什么?
后端·mysql
小成很成7 小时前
mysql 8.0.21 升级 mysql 8.0.45(经过生产环境验证)
android·mysql·adb
东风破_7 小时前
从 0 设计一个博客数据库:用户、头像与文章表应该怎么建?
后端·mysql
保定公民8 小时前
达梦数据库存储过程中的数组类型详解:基础数组与记录数组的差异化应用
数据库·达梦·存储过程·达梦数据库·dm8·dm
梦Arrebol8 小时前
Redis 内容及相关实验
数据库·redis
大模型码小白9 小时前
Spring AI Tool 实现自然语言操作 MySQL 数据库详解
服务器·开发语言·数据库·人工智能·python·mysql·spring
云计算DevOps-韩老师10 小时前
【MySQL运维DBA】【SQL基础系列002篇】
运维·mysql·dba
DBA大董10 小时前
TDengine3.0 DBA常用的运维命令和SQL2
运维·数据库·时序数据库·dba·tdengine