MySQL子查询的一些练习(未完)
短信预约 信息系统项目管理师 报名、考试、查分时间动态提醒
1.查询平均工资最低的部门的信息和该部门的平均工资
SELECT中用相关子查询
方式一:
SELECT *,(SELECT AVG(salary) FROM employees t3 WHERE t3.department_id = t1.department_id) "AVG_SAL"
FROM employees t1
WHERE t1.department_id = (SELECT department_id #找最低部门的ID
FROM employees t2
GROUP BY department_id
HARING AVG(salary) = (SELECT MIN(avg_sal) #找部门的最低工资
FROM(SELECT AVG(salary) avg_sal #找部门的平均工资
FROM employees
GROUP BY department_id
) "t_dept_avg_sal"
)
);
方式二:使用ALL
SELECT *,(SELECT AVG(salary) FROM employees t3 WHERE t3.department_id = t1.department_id) "AVG_SAL"
FROM employees t1
WHERE t1.department_id = (SELECT department_id #找最低部门的ID
FROM employees t2
GROUP BY department_id
HARING AVG(salary) <= ALL (SELECT AVG(salary)
FROM employees
GROUP BY department_id
)
);
方式三:使用LIMIT
SELECT t1.*,(SELECT AVG(salary) FROM employees t3 WHERE t3.department_id = t1.department_id) "AVG_SAL"
FROM employees t1
WHERE t1.department_id = (SELECT department_id #找最低部门的ID
FROM employees t2
GROUP BY department_id
HARING AVG(salary) = (SELECT AVG(salary)
FROM employees #直接显示出所要的数据(最低工资)
GROUP BY department_id
ORDER BY AVG(salary) ASC
LIMIT 0,1
)
);
方式四:多表的连接
SELECT *,(SELECT AVG(salary) FROM employees t3 WHERE t3.department_id = t1.department_id) "AVG_SAL"
FROM employees t1 JOIN (SELECT department_id,AVG(salary)
FROM employees t2 #将已经查出最低工资部门的信息作为一张表
GROUP BY department_id
ORDER BY AVG(salary) ASC
LIMIT 0,1
)"t_dept_avg_sal"
ON t1.department_id = t_dept_avg_sal.department_id;
2.查询公司manger的id
#方式一:自连接
SELECT DISTINCT t1.empolye_id,
FROM employees t1 JOIN employees t2
WHERE t1.employee_id = t2.manger_id;
#子查询
SELECT T1.employee_id
FROM emplpoyees t1
WHERE t1.employee_id IN (SELECT DISTINCT t2.manger_id
FROM employees t2
);
#使用EXISTS 有 (NOT)IN 的时候通常可以改成 (NOT)EXISTS
SELECT T1.employee_id
FROM emplpoyees t1
WHERE EXISTS(SELECT *
FROM employees t2
WHERE t1.employee_id = t2.manger_id
);
3.查询各个部门 中最高工资中最低的那个部门的 最低工资是多少 (与第一题类似,方法在这里就只写一种了)
#思路:先找出每个部门工资最高的数,再找其中工资最低的部门,然后在该部门中寻找低的工资
SELECT MIN(salary)
FROM emplpyees
WHERE deparment_id = (SELECT deparment_id #找到部门的ID
FROM employees
GROUP BY depaetment_id
HARING MAX(salary) = (SELECT max(salary) max_sal FROM employees #找到最高工资中最低的那个部门的工资
GROUP BY department_id
ORDER BY max_sal ASC
LIMIT 1
)
);
原文地址:https://www.cnblogs.com/wht-de-bk/archive/2022/03/07/15977830.html
免责声明:
① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。
② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341