开发者

How do I do a JPQL SubQuery?

It is possible to do the equiva开发者_如何学Golent of this sql query in JPQL?

SELECT * 
 FROM COUNTRIES c WHERE COUNTRY_ID IN (
  SELECT DISTINCT COUNTRY_ID 
   FROM PORTS p 
   WHERE p.COUNTRY_ID = c.COUNTRY_ID AND STATE = 'A'
) 


You need to test it with IN and subquery since both do work in JPQL (according to syntax reference they do work together). You may also look at MEMBER OF expressions.

But there is a better approach in my opinion. Such queries are called correlated sub-queries and one can always re-write them using EXISTS:

SELECT * FROM COUNTRIES c WHERE 
EXISTS (
        SELECT 'found' FROM PORTS p 
        WHERE p.COUNTRY_ID = c.COUNTRY_ID AND STATE = 'A'
) 

JPQL supports EXISTS with subqueries.


Yes, It is possible to use subquery with IN operator in JPQL. I had a similar usecase and it worked for me. My query was as follows.

@Query("SELECT g FROM Group g WHERE g.id IN (SELECT DISTINCT m.groupId FROM Member m WHERE m.id IN (?1))")
List<Group> findAllGroupsOfMembers(List<BigInteger> memberIds);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜