(十五)MySQL语法-子查询(三)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
四:放在exisit后面的select 查询语句(称为相关子查询)
select EXISTS(select employee_id from employees);--结果:1
select EXISTS(select employee_id from employees where salary='过家家');--结果:0
由此可见exists返回的是Boolean类型的值,其中1:有  0:没有
 
案例1:查询有员工的部门名
select d.department_name from departments d where EXISTS(
    select * from employees e where e.department_id=d.department_id
);
 
案例2;查询没有女朋友的男神信息
#使用in的方式进行查询
use girls
select * from boys bo where bo.id not in(
    select b.boyfriend_id from beauty b--注意:后面不能再加where,关联条件了
) ;
#使用exists 子查询
select * from boys bo where not EXISTS(
    select * from beauty b where b.boyfriend_id=bo.id--注意:EXISTS后面必须得加连接条件
) ;
 
练习题案例
查询各部门中工资比本部门平均工资高的员工的员工号、姓名、工资
首先,查询本部门的平均工资
select avg(salary),department_id from employees  GROUP BY department_id;
最后,连接刚刚查询出来的结果集,和employees表,进行筛选
select e.employee_id,e.salary,e.last_name,e.department_id from employees e INNER JOIN (
    select avg(salary) ag,department_id dd from employees GROUP BY department_id
) avg on avg.dd=e.department_id
where e.salary>avg.ag;
 
案例:查询管理者是king的员工姓名和工资
首先;查询姓名为king的员工编号
select employee_id from employees where last_name='king';
最后查询哪个员工的manager_id=刚刚查询出来的employee_id
select last_name,salary from employees where manager_id in(
    select employee_id from employees where last_name='king'
);

  

posted on   ~码铃薯~  阅读(200)  评论(0编辑  收藏  举报

编辑推荐:
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
阅读排行:
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示