数据在 MySQL查询练习一
6.显示各部门名和该部门的职工平均工资
SELECT d.deptname ,AVG(s.salary) FROM departments d ,employees e ,salary s WHERE d.deptid = e.deptid AND
e.empid = s.empid GROUP BY d.deptname ;
解题思路: 要求显示部门名 需要分组 group by 需要求平均工资 AVG()
需要查询三张表 关系确认 部门表的deptid=员工表的deptid,员工表的empid=工资表的empid
SELECT d.deptname ,AVG(s.salary) FROM -- 平均工资 AVG(s.salary)
departments d ,employees e ,salary s WHERE d.deptid = e.deptid AND -- 关联关系
e.empid = s.empid GROUP BY d.deptname ; -- 部门分组
7.显示工资最高的前3名职工的职工号和姓名
SELECT e.empname ,s.salary from employees e left join salary s on e.empid = s.empid
ORDER by s.salary desc limit 0,3;
解题思路:
SELECT e.empname ,s.salary from -- 要显示的内容 工号和姓名
employees e left join salary s on e.empid = s.empid -- 左连接 关联一下
ORDER by s.salary desc limit 0,3; -- 工资最高 排序一下 要求前3名 limit 显示前3各
8.列出工资在1000-2000之间的所有职工姓名
SELECT e.empname from employees e right join salary s on e.empid = s.empid
WHERE s.salary BETWEEN 1000 and 2000 ;
解题思路:
SELECT e.empname from -- 要显示的内容 姓名
employees e right join salary s on e.empid = s.empid -- 右连接 关联一下
WHERE s.salary BETWEEN 1000 and 2000 ; -- 条件工资在1000-2000
9.列出工资比王昭君高的员工
SELECT e.empname FROM employees e inner join salary s on e.empid = s.empid WHERE s.salary >
(SELECT salary FROM salary s WHERE empid = 1);
解题思路:
SELECT e.empname FROM -- 要显示的内容 姓名
employees e inner join salary s on e.empid = s.empid -- 内连接 关联一下
WHERE s.salary > -- 条件 筛选 工资大于王昭君的工资
(SELECT salary FROM salary s WHERE empid = 1); 求王昭君的工资 根据王昭君的编号1求出王昭君的工资
10.列出每个部门中工资小于本部门平均工资的员工信息
SELECT e.* from employees e ,salary s ,(SELECT d.deptid ,AVG(s.salary) as pj1 FROM salary s ,employees e ,departments d WHERE s.empid = e.empid AND e.deptid = d.deptid
GROUP BY d.deptname) pj WHERE e.empid = s.empid AND pj.deptid =e.deptid AND s.salary < pj.pj1;
解题思路: 先查询部门的平均工资 在查询每个人的工资
SELECT e.* from -- 要看的员工信息
employees e ,salary s ,
(SELECT d.deptid ,AVG(s.salary) as pj1 FROM salary s ,employees e ,departments d WHERE s.empid
= e.empid AND e.deptid = d.deptid
GROUP BY d.deptname) pj -- 把部门的平均工资当作是一张表 然后三表关联
WHERE e.empid = s.empid AND pj.deptid =e.deptid
AND s.salary < pj.pj1; -- 条件 小于部门的平均工资 注意平均工资表里的工资 需要先起一个别名