Mysql之子查询
(随手记录学习笔记)
子查询是将一个查询语句嵌套在另一个查询语句中。
子查询中可以包含:in、not in 、exists等关键字。
其基本格式为:
select 字段 from 表1 where 字段1 运算符 (select 字段2 from 表2 判断条件)
下边我们来看:
建表过程参考这里:https://blog.youkuaiyun.com/m0_50481455/article/details/114285907
1.带in关键字的子查询:
# 查询平均年龄在25岁>以上的部门名称:
select name from department where id in (select dep_id from employee group by dep_id having avg(age)>25);
# 查询技术部门员工的姓名
select * from employee where dep_id in (select id from department where name = '技术');
# 查看不足1人的部门名
select name from department where id not in (select distinct dep_id from employee );
运行结果如下:
2.带比较运算符的子查询:
比较运算符,就是>、<、=这种,下边我们来看案例:
# 查询大于所有人平均年龄的员工名与年薪
select name,age from employee where age > (select avg(age) FROM employee);
运行结果如下:
3.带exists关键字的子查询:
# 查询department表是否存在dept_id=203,Ture
select * from employee where exists (select id from department where name = '技术')
运行结果如下:
觉得本篇文章对你有帮助的话,可以给作者点个赞鼓励一下~谢谢。您的支持就是我前进路上的最大动力。