使用条件查询/休眠查询选择最大ID行的问题? [英] Issue with selecting max id rows using criteria query / hibernate query?

查看:85
本文介绍了使用条件查询/休眠查询选择最大ID行的问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法选择相应学生的TestId为max的行,我编写了如下代码,但未获得所需的输出。我的代码如下,

 条件c = sessionFactory.getCurrentSession()。createCriteria(student.class).setProjection(Projections。 projectionList()。add(Projections.property( answer), answer))); 
c.add(Restrictions.eq( surveyId,send_Survey));
//c.add(Restrictions.eq(\"testId, 1));
//c.setProjection(Projection.max(\"testId));
c.addOrder(Order.desc( testId)));
c.add(Restrictions.eq( questionid,FinalQuestionsOne));
List< String> age = c.list();

我的表结构如下,





我需要以下内容输出。选择最大TestId的答案列。如何使用条件查询获取输出



解决方案

所以我认为您可以通过以下sql来实现:

  SELECT TestId,MAX(answer)WHERE QuestionId = 1 GROUP BY TestId; 

您应该可以使用以下Hibernate实现此功能:

  sessionFactory.getCurrentSession()。createCriteria(student.class).setProjection(Projections.projectionList()
.add(Projections.property( TestId)) , TestId)
.add(Projections.groupProperty( TestId))
.add(Projections.max( answer))));


I am unable to select the rows where TestId is max for respective student, I wrote the code as follows which does not get the required output. my code is as follows,

Criteria c = sessionFactory.getCurrentSession().createCriteria(student.class).setProjection(Projections.projectionList().add(Projections.property("answer"),"answer"));
c.add(Restrictions.eq("surveyId",send_Survey));
//c.add(Restrictions.eq("testId", "1" ));
//c.setProjection(Projection.max("testId"));
c.addOrder(Order.desc("testId"));
c.add(Restrictions.eq("questionid",FinalQuestionsOne));
List<String> age=c.list();

My table structure is as follows,

I need the following output. select the answer column for max TestId's. How can I get the output using criteria query

解决方案

So I think what you're trying to get can be achievedd by the following sql:

SELECT TestId, MAX(answer) WHERE questionId = 1 GROUP BY TestId;

You should be able to achieve this with the following Hibernate:

sessionFactory.getCurrentSession().createCriteria(student.class).setProjection(Projections.projectionList()
                        .add(Projections.property("TestId"), "TestId")
                        .add(Projections.groupProperty("TestId"))
                        .add(Projections.max("answer")));

这篇关于使用条件查询/休眠查询选择最大ID行的问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆