MySQL学习笔记篇九
作者:互联网
1、什么是子查询?
一个select语句中包含另一个完整的select语句或两个以上select;
2、子查询出现的位置:
where后,把select查询出的结果当作另一个select的条件值;
from后,把查询出的结果当作一个新表;
3、where形式举例:
假设有员工表employer表如下:
id | name | job | shangji | hiredate | salary | reward | dep_id |
1100 | 张一 | 经理 | 1104 | 2020-10-12 | 15000 | 300 | 00 |
1101 | 张二 | 客服 | 1105 | 2019-09-09 | 8000 | 01 | |
1102 | 张三 | 客服 | 1103 | 2017-09-23 | 8000 | 02 | |
1103 | 李四 | 业务人员 | 1100 | 2020-11-09 | 7800 | 500 | 03 |
1104 | 王五 | 经理 | 2021-01-06 | 17800 | 00 | ||
1105 | 赵六 | 业务人员 | 1100 | 2021-03-28 | 7800 | 03 | |
1106 | 赵七 | 客服 | 1104 | 2020-06-26 | 8000 | 02 |
部门表department表如下:
dep_id | name | local |
00 | 客服部 | 北京 |
01 | 业务部 | 上海 |
02 | 运营部 | 广州 |
03 | 销售部 | 青岛 |
薪水等级表SG表如下:
grade | lowsalary | highsalary |
1 | 1000 | 5000 |
2 | 5001 | 9000 |
3 | 9001 | 13000 |
4 | 13001 | 17000 |
5 | 17001 | 21000 |
查询与张三同一个部门的员工:
Select dep_id from employer where name='张三';
Select name from employer where dep_id='20';
Select name from employer where dep_id=(select dep_id from employer where name='张三');
from形式举例:
查询03号部门工资大于7000的员工;
Select name ,salary,dep_id from employer where dep_id=03;
Select name from (select name,salary,dep_id from employer where dep_id=03) s where s.salary>7000;
子查询练习:
查询工资高于张二的员工:分解步骤
a.查询张二的工资:
Select salary from employer where name='张二';
b.再根据查出的结果查询大于该值的记录员工名称:
Select name from employer where salary>(select salary from employer where name='张二');
查询工资高于03号部门所有员工的信息;
a.先查询03号部门的工资最高的人:
Select MAX(salary) from employer where dep_id=03 ;
b.再到整个表中查询大于03号部门工资最高的那些人:
select name, salary from employer where salary>(select max(salary) from employer where dep_id=03);
查询岗位和工资与赵七完全相同的员工:
分解a.查询赵七的岗位和工资;
Select job,salary where employer name='赵七';
分解b.根据查询出的结果等于该值的员工名字;
Select * from employer where (salary , job) in (Select job,salary where employer name='赵七');
方法二:select * from employer e,(select job,salary where employer name='赵七') r where e.job=r.job and e.salary=r.salary;
有两个以上直接下属的员工信息:
分析:Select shangji,group_concat(shangji),count(shangji) from employer group by shangji having count(shangji)>=2;
Select * from employer where id in (Select shangji from employer group by shangji having count(shangji)>=2);
查询员工编号为 1106的员工名、员工工资、部门名称、部门地址;
Select e.name,e.salary,d.local,d.name from employer e,department d where e.dep_id=d.dep_id and e.id=1106;
标签:salary,name,笔记,employer,学习,MySQL,where,id,Select 来源: https://blog.csdn.net/weixin_42204220/article/details/123056937