数据库多表连接查询练习
一、创建数据库dept、emp
二、插入数据
1.找出销售部门中年纪最大的员工的姓名
mysql> select name,age from emp
inner join dept on dept.dept1=emp.dept2
where dept_name='销售'
order by age desc limit 1;
2.求财务部门最低工资的员工姓名
mysql> select name from emp
where incoming=(select min(incoming) from emp);
3.列出每个部门收入总和高于9000的部门名称
mysql> select dept_name as 部门名称,sum(incoming) as 总工资 from emp
inner join dept on emp.dept2=dept.dept1
group by dept_name having 总工资>9000;
4.求工资在7500到8500元之间,年龄最大的人的姓名及部门
mysql> select name from emp
where incoming in (7500,8500)
order by age desc limit 1;
5.找出销售部门收入最低的员工入职时间
mysql> select worktime_start from emp
inner join dept on emp.dept2=dept.dept1
where dept_name='销售'
order by incoming limit 1;
6.财务部门收入超过2000元的员工姓名
mysql> select name as 姓名 from emp
inner join dept on emp.dept2=dept.dept1
where dept_name='财务' and incoming>2000;
7.列出每个部门的平均收入及部门名称
mysql> select dept_name as 部门名称, avg(incoming) as 平均工资 from emp
-> inner join dept on emp.dept2=dept.dept1
-> group by dept_name;
8.IT技术部入职员工的员工号
mysql> select sid from emp
-> inner join dept on emp.dept2=dept.dept1
-> where dept_name='IT技术';
9.财务部门的收入总和;
mysql> select sum(incoming) as 收入总和 from emp
-> inner join dept on emp.dept2=dept.dept1
-> where dept_name='财务';
10.先按部门号大小排序,再依据入职时间由早到晚排序员工信息表
mysql> select * from emp order by dept2 desc,worktime_start;
11.找出哪个部门还没有员工入职;
mysql> select dept_name from emp right join dept on emp.dept2=dept.dept1 where sid is null;
12.列出部门员工收入大于7000的部门编号,部门名称;
mysql> select dept2 as 部门编号,dept_name as 部门名称 from emp
-> inner join dept on emp.dept2=dept.dept1
-> where incoming>7000;
13.列出每一个部门的员工总收入及部门名称;
mysql> select dept_name as 部门名称,sum(incoming) as 总收入 from emp -> inner join dept on emp.dept2=dept.dept1 -> group by dept_name;
14.列出每一个部门中年纪最大的员工姓名,部门名称;
mysql> select emp.name as 姓名, dept.dept_name as 部门名称 from dept
-> inner join (select max(age) as age,dept2 from emp group by dept2) as em on dept.dept1=em.dept2
-> inner join emp on dept.dept1=emp.dept2 and em.age=emp.age;
15.求李四的收入及部门名称
mysql> select incoming as 收入,dept_name from emp
-> inner join dept on emp.dept2=dept.dept1
-> where name='李四';
16.列出每个部门中收入最高的员工姓名,部门名称,收入,并按照收入降序
mysql> select name as 姓名,incoming as 收入,dept_name as 部门名称 from emp
-> inner join dept on emp.dept2=dept.dept1 -> inner join
-> (select max(incoming) as max_incom, dept2 from emp group by dept2)
-> as em
-> on emp.dept2=em.dept2 and emp.incoming=em.max_incom
-> order by incoming desc;
17.列出部门员工数大于1个的部门名称
mysql> select dept_name as 部门名称 from dept
-> inner join (select count(*) as 员工数,dept2 from emp group by dept2) -> as de on dept.dept1=de.dept2
-> where de.员工数>1;
19.查找张三所在的部门名称
mysql> select dept_name as 部门名称 from emp
-> inner join dept on emp.dept2=dept.dept1
-> where name='张三';