子查询 1. 什么是子查询 -- 需求:查询开发部中有哪些员工 select * from emp; -- 通过两条语句查询 select id from dept where name="开发部" ;
-- 需求:查询开发部中有哪些员工
select * from emp;
-- 通过两条语句查询
select id from dept where name="开发部" ;
select * from emp where dept_id = 1;
-- 使用子查询
select * from emp where dept_id = (select id from dept where name="市场部");
子查询结果只要是单行单列,肯定在 WHERE 后面作为条件,父查询使用:比较运算符,如:> 、<、<>、=等
SELECT 查询字段 FROM 表 WHERE 字段= (子查询);
-- 1) 查询最高工资是多少
select max(salary) from emp;
-- 2) 根据最高工资到员工表查询到对应的员工信息
select * from emp where salary = (select max(salary) from emp);
-- 1) 查询平均工资是多少
select avg(salary) from emp;
-- 2) 到员工表查询小于平均的员工信息
select * from emp where salary < (select avg(salary) from emp);
子查询结果是单例多行,结果集类似于一个数组,父查询使用 IN 运算符
SELECT 查询字段 FROM 表 WHERE 字段 IN (子查询);
-- 先查询大于 5000 的员工所在的部门 id
select dept_id from emp where salary > 5000;
-- 再查询在这些部门 id 中部门的名字 Subquery returns more than 1 row
select name from dept where id = (select dept_id from emp where salary > 5000);
select name from dept where id in (select dept_id from emp where salary > 5000);
-- 先查询开发部与财务部的 id
select id from dept where name in("开发部","财务部");
-- 再查询在这些部门 id 中有哪些员工
select * from emp where dept_id in (select id from dept where name in("开发部","财务部"));
子查询结果只要是多列,肯定在 FROM 后面作为表
SELECT 查询字段 FROM (子查询) 表别名 WHERE 条件;
子查询作为表需要取别名,否则这张表没有名称则无法访问表中的字段
-- 查询出 2011 年以后入职的员工信息,包括部门名称
-- 在员工表中查询 2011-1-1 以后入职的员工
select * from emp where join_date >="2011-1-1";
-- 查询所有的部门信息,与上面的虚拟表中的信息组合,找出所有部门 id 等于的 dept_id
select * from dept d, (select * from emp where join_date >="2011-1-1") e where d.`id`= e.dept_id ;
也可以使用表连接:
select * from emp inner join dept on emp.`dept_id` = dept.`id` where join_date >="2011-1-1";
select * from emp inner join dept on emp.`dept_id` = dept.`id` and join_date >="2011-1-1";
--结束END--
本文标题: MySQL总结(十一)子查询-详解
本文链接: https://www.lsjlt.com/news/6631.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-05-15
2024-05-15
2024-05-15
2024-05-15
2024-05-15
2024-05-15
2024-05-15
2024-05-15
2024-05-14
2024-05-14
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0