我想转换SQL语句
SELECT * FROM (SELECT * FROM `votes` ORDER BY `date` DESC) AS sub GROUP BY `username`
进入JPQL。我们的想法是为每个用户(GROUP BY date
)获取最新的投票(ORDER BY username
DESC)。
我知道JPQL不支持FROM中的子查询,所以我尝试了“IN”
# does not work!
SELECT v FROM Vote v WHERE v.id IN (SELECT tmp.id FROM Vote tmp ORDER BY date DESC) GROUP BY v.username
但这给了我第一个参赛作品。然后我尝试了“MAX”
# does not work!
SELECT v FROM Vote v WHERE v.date IN (SELECT MAX(tmp.date) FROM Vote tmp GROUP BY tmp.username)
同样,但这给了我同一个用户的多个条目date
不是唯一的...
修改
我想过用SQL语法创建一个VIEW作为一种解决方法,但是由于JPQL查询引用了类(而不是表),这并没有让我走得太远; - )
修改
然后我想到了JOIN和lead me to Native Queries。事实证明我可以将上述SQL与nativeQuery = true
:
@Query(value = "SELECT * FROM (SELECT * FROM `votes` ORDER BY `date` DESC) AS sub GROUP BY `username`", nativeQuery = true)
这有效!
答案 0 :(得分:0)
请参阅最终更新:如果使用nativeQuery = true
,则可以使用初始SQL语句 - 当然,代码将不可移植,因为本机查询绑定到(当前)数据库类型
谢谢!