如何基于字段查询具有单个子对象的表中的对象的sql?

问题描述 投票:0回答:1

我现在拥有的是:

与所有社区等获得List<Town>

(Town) em.createQuery(from Town towns"
        + " left join fetch towns.neighborhoods neighborhood"
        + " left join fetch neighborhood.population population"
        + " left join fetch population.age age"
        + " where age.value = :ageValue")
       .setParameter("ageValue", ageValue)

我希望得到一个List<Town>只有一个邻居,这是neighborhood.creationDate的第一个。

我怎么做 ?

我不想把它们全部拿走然后删除它。

谢谢。

java mysql hibernate jpa entitymanager
1个回答
0
投票

我建议在where子句中添加一个子查询,如下所示:

where age.value = :ageValue 
    AND neighborhood.creationDate = 
         (Select max(nh.creationDate) From Neighborhood nh 
               where nh.townsId = towns.townsId)
© www.soinside.com 2019 - 2024. All rights reserved.