分组查询各个部门根据部门下工资最高和工资最低的人员姓名、和工资金额的Java mybatis代码实现
时间: 2024-06-01 08:12:52 浏览: 38
以下是Java MyBatis实现根据部门查询工资最高和最低人员的代码示例:
先定义一个ResultMap,用来表示查询结果:
<resultMap id="departmentSalaryMap" type="Department">
<id column="department_id" property="id" />
<result column="department_name" property="name" />
<association property="highestSalaryEmployee" javaType="Employee">
<id column="highest_salary_employee_id" property="id" />
<result column="highest_salary_employee_name" property="name" />
<result column="highest_salary" property="salary" />
</association>
<association property="lowestSalaryEmployee" javaType="Employee">
<id column="lowest_salary_employee_id" property="id" />
<result column="lowest_salary_employee_name" property="name" />
<result column="lowest_salary" property="salary" />
</association>
</resultMap>
然后在Mapper中定义查询语句:
<select id="selectDepartments" resultMap="departmentSalaryMap">
SELECT d.id AS department_id,d.name AS department_name,
hse.id AS highest_salary_employee_id,hse.name AS highest_salary_employee_name,hse.salary AS highest_salary,
lse.id AS lowest_salary_employee_id,lse.name AS lowest_salary_employee_name,lse.salary AS lowest_salary
FROM department d LEFT JOIN employee hse ON hse.id = (SELECT id FROM employee WHERE department_id = d.id ORDER BY salary DESC LIMIT 1)
LEFT JOIN employee lse ON lse.id = (SELECT id FROM employee WHERE department_id = d.id ORDER BY salary ASC LIMIT 1)
</select>
解释一下查询语句的含义:
首先以部门为基础表,使用LEFT JOIN关联子查询,查询出每个部门下工资最高和工资最低的员工信息。
以最高工资的查询为例:在子查询中,先根据部门ID查询所有员工的记录,按照工资降序排列,然后LIMIT 1,只取第一条记录,即为该部门下工资最高的员工记录。
然后LEFT JOIN中第一次关联员工表,使用别名hse,关联最高工资的员工记录。
最后LEFT JOIN中第二次关联员工表,使用别名lse,关联最低工资的员工记录。
这样每个部门所查询到的结果都是包含最高和最低工资员工信息的Department对象。
当然,需要在Department类中定义highestSalaryEmployee和lowestSalaryEmployee两个属性,类型为Employee,并提供相应的getter和setter方法,才能正确加载查询结果。
阅读全文