肖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

相关推荐
努力努力再努力wz7 分钟前
【MySQL入门系列】:不只是建表:MySQL 表约束与 DDL 执行机制全解析
android·linux·服务器·数据结构·数据库·c++·mysql
m0_7164300712 分钟前
如何在MongoDB中监控集群中的僵尸连接_释放长时间不活跃的游标资源
jvm·数据库·python
m0_7164300713 分钟前
HTML函数开发最低配置是多少_HTML函数入门硬件门槛【指南】
jvm·数据库·python
Chasing__Dreams16 分钟前
Mysql--基础知识点--109--SERIALIZABLE事务隔离级别
数据库·mysql
隐于花海,等待花开22 分钟前
窗口函数之排序函数详细解读及示例
大数据·数据库·hive
亚空间仓鼠23 分钟前
关系型数据库MySQL(四):读写分离
android·数据库·mysql
Wyz2012102432 分钟前
SQL中如何处理GROUP BY的不可排序问题_ORDERBY与聚合
jvm·数据库·python
Polar__Star38 分钟前
jsoup如何读取html
jvm·数据库·python
亚空间仓鼠40 分钟前
关系型数据库MySQL(三):主从复制
数据库·mysql
a95114164241 分钟前
怎么防范通过phpMyAdmin上传WebShell_禁止into outfile权限
jvm·数据库·python