我有一个包含id和date列的表。 目前,每个具有不同日期的ID有10条记录。我想为每个ID 获取最新的3条记录。当我在命令行上运行查询时,它按预期工作并返回正好3条记录。但是当我使用 Spring JDBC Template运行相同的查询时,它会返回每个id 的所有10条记录。 我的查询如下: -
SELECT
`ranked`.`ID`,
`ranked`.`DATE`
FROM
(SELECT
`stk`.`id` AS ID,
`stk`.`date` AS DATE,
@id_rank := IF(@current_id = `stk`.`id`,@id_rank + 1,1) AS id_rank,
@current_id := `stk`.`id`
FROM
stack stk
ORDER BY `stk`.`id` ASC,
`stk`.`date` DESC) ranked
WHERE ranked.id_rank <= 3
我的Java代码是这样的: -
public static final String ID_FILTER_QUERY = "SELECT `ranked`.`ID`, `ranked`.`DATE` FROM "
+ "(SELECT `stk`.`id` AS ID, `stk`.`date` AS DATE, @id_rank := IF(@current_id = `stk`.`id`,@id_rank + 1,1) AS id_rank,"
+ "@current_id := `stk`.`id` FROM stack stk ORDER BY `stk`.`id` ASC, `stk`.`date` DESC) ranked WHERE ranked.id_rank <= 3";
public List<StackDTO> getStackGroupById() {
return jdbcTemplate.query(Queries.ID_FILTER_QUERY, new IdMapper());
}
是否有其他方法可以获取每个ID或每组的最后3条记录?