肖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

相关推荐
isNotNullX1 分钟前
智能问数技术路线怎么选?从Text-to-SQL到Data Agent一次讲清
数据库·oracle
鸽芷咕3 分钟前
换库不申请停机窗口?金仓KFS数据集成软件双轨并行,还真行
数据库
catino12 分钟前
分库分表详解
mysql
鸽芷咕14 分钟前
月底报表又把库拖垮了?聊聊金仓数据库KES的列存储和真本事
数据库
Juicedata17 分钟前
面向 EB 级 AI 存储:JuiceFS 企业版架构演进
数据库·人工智能·架构
数据库小学妹22 分钟前
MySQL表碎片与 OPTIMIZE TABLE:空间回收的代价与边界
数据库·后端·mysql
java_logo28 分钟前
Docker 部署 Hue:轻松搭建数据库与数据仓库 SQL 查询平台
数据库·数据仓库·sql·docker·hue·部署教程·轩辕镜像
Davina_yu32 分钟前
1、count(*)、count(1) 和 count(单个字段) 的区别
数据库
锦衣夜行?32 分钟前
Oracle 数据库安装失败清理残留步骤
数据库·oracle
时间售卖铺1 小时前
MySQL 表的约束
运维·数据库·mysql·云原生