0

我有一个非实体类

public class CountryStatistics {

    public CountryStatistics(Long numTowns, Long numVillages) {
    ...
    }

}

对于给定的国家,我想构建一个统计对象。

国家、村庄和城市是实体,所以我按照下面的代码尝试了一些事情。

String queryString = 
"SELECT NEW mypackage.CountryStatistics(count(t), count(v)) 
 FROM Town t, Village v WHERE t.country = :country AND v.country = :country"

TypedQuery<CountryStatistics> query = 
em.createQuery(queryString ,CountryStatistics.class).setParameter("country", country);

query.getSingleResult()

问题:在同一查询中计算不同表中的某些实体的正确方法是什么?

通过上面的查询,如果我像下面这样区分,我最终会得到很高的数字,城镇的数量将是正确的。

"SELECT NEW mypackage.CountryStatistics(count(distinct t), count(v)) 
 FROM Town t, Village v WHERE t.country = :country AND v.country = :country"

但是,如果我将它设置为村庄,我也会得到:

java.sql.SQLSyntaxErrorException: Multiple DISTINCT aggregates are not supported at this time.
4

1 回答 1

2

以下查询(未测试)应该做你想做的事:

select count(distinct t.id), count(distinct v.id) from Country c
left join c.towns t
left join c.villages v
where c.id = :countryId
于 2013-03-23T13:57:48.017 回答