select
main_id as requestId,
check_id,
check_style,
batch_index,
check_datetime
from mm_request_check
where
is_delete = 0
and check_eid = #{employeeSuit.eId}
and (main_id, batch_index) in (
select
main_id,
max(batch_index) as max_batch_index
from
mm_request_check
where
is_delete = 0
and check_eid = #{employeeSuit.eId}
and main_id in
#{item.requestId}
group by main_id
)
是否可以改为使用 row_number()方法实现
————————————————————————————————
实现方式:
可以使用 ROW_NUMBER() 窗口函数来实现这一需求。ROW_NUMBER() 窗口函数可以帮助我们为每个 main_id 分区内的行按 batch_index 降序排列,并为每个分区内的行分配一个唯一的行号,从而可以轻松选择 batch_index 最大的行。
使用 ROW_NUMBER() 方法实现的查询
select
requestId,
check_id,
check_style,
batch_index,
check_datetime
from (
select
main_id as requestId,
check_id,
check_style,
batch_index,
check_datetime,
row_number() over (partition by main_id order by batch_index desc) as rn
from
mm_request_check
where
is_delete = 0
and check_eid = #{employeeSuit.eId}
and main_id in
#{item.requestId}
) as subquery
where rn = 1
解释
内部查询使用 ROW_NUMBER() 窗口函数按 main_id 分区,并按 batch_index 降序排列。
为每个分区的行分配一个行号 rn。
外层查询过滤出 rn = 1 的行,即每个 main_id 分区中 batch_index 最大的行。
保证接口的一致性
确保 Mapper 接口和 Java 方法调用保持一致。
Mapper 接口
List addCheckIdToMainId(
@Param(“searchRequisitionList”) List searchRequisitionList,
@Param(“employeeSuit”) EmployeeSuit employeeSuit
);
Java 方法调用
在 Java 方法中调用此查询并传递参数:
List resultList = mmRequestCheckMapper.addCheckIdToMainId(searchRequisitionList, employeeSuit);
这样可以确保查询正确地返回 main_id 相同且 batch_index 最大的数据。