JPQL Selecting Record with Max Value

2019-05-10 22:16发布

I'm trying to select the record that has the max value for a particular column and here's what I have so far:

select o from Order o 
    where o.orderNumber = :orderNumber
    and o.version =
        (select max(o.version) from Order o where o.orderNumber = :orderNumber)

This seems to be generating the SQL:

SELECT *
FROM   Order
WHERE  ordernumber = :orderNumber
       AND orderversion = (SELECT Max(orderversion)
                           FROM   order
                           WHERE  ordernumber = :orderNumber);

I think the following SQL would be more efficient:

SELECT *
FROM   order ord
       INNER JOIN (SELECT ordernumber,
                          Max (version) AS version
                   FROM   order
                   WHERE  ordernumber = :ordernumber
                   GROUP  BY ordernumber) mx
         ON ord.ordernumber = mx.ordernumber
            AND ord.version = mx.version; 

Is there anyway I can express this in JPQL?

(Most answers online for questions related to selecting record with max value on a particular field seem to suggest the above JPQL I had presented...)

1条回答
可以哭但决不认输i
2楼-- · 2019-05-10 23:06

No, it's not possible to generate the above SQL query with HQL. The documentation says:

Note that HQL subqueries can occur only in the select or where clauses.

查看更多
登录 后发表回答