在JPQL中是否可以匹配多个列的IN子查询?

时间:2013-06-20 12:40:13

标签: java jpa jpql

我有一个SQL查询我正在尝试转换为JPQL。查询如下:

SELECT *
FROM MyTable
WHERE (myFirstColumn, mySecondColumn) IN (
    SELECT myFirstColumn, max(mySecondColumn)
    FROM MyTable
    GROUP BY myFirstColumn
)

我的转化尝试很简单:

select myObject
from MyObject as myObject
where (myObject.myFirstValue, myObject.mySecondValue) in (
    select subMyObject.myFirstValue, max(subMyOject.mySecondValue)
    from MyObject as subMyObject
    group by subMyObject.myFirstValue
)

MyObject映射到MyTable(使用注释)。

如果我理解IN语句(http://openjpa.apache.org/builds/1.2.3/apache-openjpa/docs/jpa_langref.html#jpa_langref_in)上的JPQL文档,而我真的不确定,那么这种直接转换是不可能的。还有另外一种方法吗?

2 个答案:

答案 0 :(得分:1)

也许您可以稍微更改一下查询。您可以使用EXISTS而不是IN。

select myObject
from MyObject myObject
where exists
( 
   select subMyObject.myFirstValue, max(subMyOject.mySecondValue) 
   from MyObject subMyObject 
   where myObject.myFirstValue = subMyObject.myFirstValue 
   group by subMyObject.myFirstValue 
   having max(subMyOject.mySecondValue) = myObject.mySecondValue

) 

答案 1 :(得分:0)

最后,我找不到一种方法让Java做了繁重的工作(即将第二个值排序并找到最大值)。它不是那么漂亮但它有效。