肖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

相关推荐
Database_Cool_8 分钟前
AnalyticDB MySQL vs Apache Doris:企业级云数仓如何选型——全维度对比指南
数据库·数据仓库·mysql·阿里云
心翼叶少9 分钟前
Redis(二):设置密码
数据库·redis·缓存
_Kafka_13 分钟前
Oracle平均成本计算流程
数据库·oracle
xfhuangfu14 分钟前
Oracle 19c中业务表的列发生变化时使用impdp
数据库·oracle
小何code37 分钟前
【Python零基础入门】第10篇:Python列表方法与应用实例
数据库·人工智能·python
Flash.kkl1 小时前
C++基于websocketpp的多用户网页五子棋项目
开发语言·网络·数据库·c++·websocket·mysql
kong@react1 小时前
milvus(向量数据库)docker容器(升级1.0)
数据库·docker·milvus
流烟默1 小时前
国产数据库CERDB 数据库实战:核心概念与备份恢复全攻略
数据库·数据库备份·cerdb
计算机安禾1 小时前
【算法分析与设计】第44篇:随机化复杂度类:RP、BPP与去随机化猜想
java·数据结构·数据库·算法·机器学习
Leon-Ning Liu1 小时前
Oracle恢复DELETE数据的PACKAGE(介绍篇)(仅做研究使用)
数据库·oracle