SELECT * FROM [ScoreVersion] sv WHERE [Version_No] in (SELECT max([Version_No])
FROM [ScoreVersion] GROUP BY [score_id] HAVING [score_id] = sv。[score_id])
答案 0 :(得分:0)
您可以撰写DetachedCriteria
来获取score_id, max(version_no)
对的列表,并使用您的外IN( )
执行多属性Criteria
。
DetachedCriteria subQuery = DetachedCriteria.forClass(ScoreVersion.class);
subQuery.setProjection(
Projections.projectionList()
.add(Projections.groupProperty("scoreId"))
.add(Projections.max("versionNumber")
)
);
Criteria criteria = this.getSession().createCriteria(ScoreVersion.class);
criteria.add(
Subqueries.propertiesIn(new String[] {"scoreId", "versionNumber"}, subQuery)
);
最终的SQL应该是这样的:
select * from [ScoreVersion] where ([score_id], [Version_No]) in (
select [score_id], max([Version_No]) from [ScoreVersion] group by [score_id]
);
在Hibernate 4之前:
您必须在HQL中编写查询:
Query query = session.createQuery(String sql);
您的查询位于:
select sv from ScoreVersion sv
where (sv.scoreId, sv.versionNumber) in (
select sub.scoreId, max(sub.versionNumber)
from ScoreVersion sub
group by sub.scoreId
)