我需要查询以从一组记录中查找具有最新日期的记录。我尝试了很多东西,最近的东西是这样的:
select msg, msg.createdDate from ImportedMessage msg where msg.siteId = ?1 and msg.createdDate = max(msg.createdDate) group by msg.createdDate
不幸的是,我尝试的所有内容都产生了某种错误。我似乎得到的最大错误是:
Caused by: java.sql.SQLException: Not in aggregate function or group by clause: org.hsqldb.Expression@688c688c in statement [select importedme0_.IMPORTED_MSG_ID as col_0_0_, importedme0_.CREATED_DATE as col_1_0_, max(importedme0_.CREATED_DATE) as col_2_0_, importedme0_.IMPORTED_MSG_ID as IMPORTED1_1_, importedme0_.CREATED_BY as CREATED2_1_, importedme0_.CREATED_DATE as CREATED3_1_, importedme0_.UPDATED_BY as UPDATED4_1_, importedme0_.UPDATED_DATE as UPDATED5_1_, importedme0_.IMPORT_TYPE as IMPORT6_1_, importedme0_.MESSAGE as MESSAGE1_, importedme0_.PROCESSED_FLAG as PROCESSED8_1_, importedme0_.SITE_ID as SITE9_1_ from IMPORTED_MSG importedme0_ where importedme0_.SITE_ID=? and importedme0_.CREATED_DATE=max(importedme0_.CREATED_DATE) group by importedme0_.CREATED_DATE] at org.hsqldb.jdbc.Util.throwError(Unknown Source) at org.hsqldb.jdbc.jdbcPreparedStatement.(Unknown Source) at org.hsqldb.jdbc.jdbcConnection.prepareStatement(Unknown Source) at org.hibernate.jdbc.AbstractBatcher.getPreparedStatement(AbstractBatcher.java:534) at org.hibernate.jdbc.AbstractBatcher.getPreparedStatement(AbstractBatcher.java:452) at org.hibernate.jdbc.AbstractBatcher.prepareQueryStatement(AbstractBatcher.java:161) at org.hibernate.loader.Loader.prepareQueryStatement(Loader.java:1616) at org.hibernate.loader.Loader.doQuery(Loader.java:717) at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:270) at org.hibernate.loader.Loader.doList(Loader.java:2449) ... 52 more
我相信这告诉我的是,我的select子句中没有适当的东西允许该组工作。但是,我尝试了各种各样的组合,一切都可以回到这个错误。
有人能告诉我这里我做错了什么吗?
答案 0 :(得分:10)
嗯,我想主持人没有费心去阅读推动答案的编辑: 来自提问者的关于查询意图的评论:
“我有一个表,它包含一个数据元素列表(id,message(字符串),siteId(string),createdDate(Timestamp)。我需要做的是选择siteId,然后在那里找到记录具有最新createdDate的组。“
解决方案:
Query query = entityManagerReference.createQuery(
"SELECT msg FROM ImportedMessage msg "
+ "WHERE msg.siteId = :siteId ORDER BY msg.createDate desc");
query.setParameter("siteId", 12345);
query.setMaxResults(1);
答案 1 :(得分:0)
使用Oracle10方言进入休眠状态,将其转换为WHERE ROWNUM <= 1。