Select 使用查询 DSL 记录每个组的最大值

Select record with max value from each group with Query DSL

我有一个分数 table,我有球员得分,我想要 select 每个得分最高的球员的唯一记录。

这里是 table:

id | player_id | score | ...
1  | 1         |  10   | ...
2  | 2         |  21   | ...
3  | 3         |  9    | ...
4  | 1         |  30   | ...
5  | 3         |  2    | ...

预期结果:

id | player_id | score | ...
2  | 2         |  21   | ...
3  | 3         |  9    | ...
4  | 1         |  30   | ...

我可以像这样用纯 SQL 实现:

SELECT *
FROM player_score ps
WHERE ps.score = 
(
    SELECT max(ps2.score)
    FROM player_score ps2
    WHERE ps2.player_id = ps.player_id
) 

你能告诉我如何用查询dsl实现相同的查询吗?我用 JPASubQuery 找到了一些解决方案,但是这个 class 对我不起作用(我的 IDE 无法解决这个 class)。我正在使用 querydsl 4.x。提前谢谢你。

JPASubQuery 已在 querydsl 4 中删除。改为使用 JPAExpressions.select。您的 WHERE 子句应如下所示:

.where(playerScore.score.eq(JPAExpressions.select(playerScore2.score.max())
                            .from(playerScore2))
                            .where(playerScore2.playerId.eq(playerScore.playerId)))