使用 JPQL 限制子查询
我想通过 JPA2 获取前 100 种产品的平均价格。查询应该看起来像这样(我的 sql 有点生疏):
select avg(price) from (
select p.price from Product p order by p.price desc limit 100)
但这根本不起作用。我也尝试过这个:
select avg(p.price) from Product p where p.id =
(select pj.id from Product pj order by pj.price desc limit 100)
这一直有效,直到 limit 关键字。
我读到 JPQL 中没有限制。
关于如何做到这一点有什么想法吗?标准也很好。
I'd like to get the average price of my top 100 products via JPA2. The query should look something like this (my sql is a little rusty):
select avg(price) from (
select p.price from Product p order by p.price desc limit 100)
but that is not working at all. I also tried this:
select avg(p.price) from Product p where p.id =
(select pj.id from Product pj order by pj.price desc limit 100)
this is working up until the limit keyword.
I read that limit is not available in JPQL.
Any idea on how to do this? Criteria would also be fine.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
JPQL不支持
LIMIT
。以下是使用 Criteria-API 的示例代码。或者
如果这不起作用,那么您必须执行两个查询 - 选择明确排序的记录和然后对它们进行平均。
否则,如果可移植性不是问题,请使用本机查询。您可以使用单个查询来完成相同的任务,因为许多 RDBMS 支持限制从数据库获取的结果数量。
LIMIT
is not supported by JPQL. Below is the sample-code using Criteria-API.or
If this doesn't work, then you have to go for executing two queries – selecting definitely ordered records & then averaging them.
Else, go for a native query if portability is not an issue. You can accomplish same using a single query as many RDBMSes support restricting the number of results fetched from a database.
请参阅这篇关于 JPQL LIMIT 解决方法的帖子。
See this post regarding the JPQL LIMIT work around.