肖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

相关推荐
parade岁月36 分钟前
没有称手工具了怎么办?搓一个!AI 时代顺手造了个单文件 Mermaid ER 查看器
数据库·后端
hryou09226 小时前
向量库选型别踩坑:10个候选、6个暗坑,一次说清
数据库·架构
emoji1111116 小时前
python总结
数据库
zxcvb1538 小时前
运维实践里把备份mysql数据库做稳的一些思路
运维·数据库·mysql
一级新生10 小时前
Dify 迭代节点:从输入输出到九步实操
数据库·人工智能·mysql·低代码·工作流·dify
夜雪一千11 小时前
PostgreSQL 中哪些操作可以写成自定义函数
数据库·postgresql
唐青枫12 小时前
MySQL mysql.help_topic 详解及实战 Demo
mysql
科力锐品牌君12 小时前
信创进入核心系统深水区:X86 与国产架构长期并存,如何落地统一灾备?
运维·网络·数据库·数据安全·灾备
在角落发呆12 小时前
sqlserver 如何备份数据库:从手动备份到自动定时、异地容灾的完整方案
数据库·windows·备份·数据备份
xixiaoyunya12 小时前
MySQL 全库备份:用 mysqldump 打好基线,再补上自动化与异地能力
数据库·mysql·自动化