【发布时间】:2016-04-05 19:35:37
【问题描述】:
假设我有两个表:Topic 和 Post。
Topic 有@OneToMany Set<Post> posts 这意味着一个主题可能有零个或多个回复的帖子。 (并且Post 有一个@ManyToOne Topic topic 链接回Topic)
Topic 和 Post 都有一个 created 列,用于存储时间戳。
我想得到按最新回复发帖时间排序的主题列表,如果某个主题没有回复帖子,则根据主题创建时间判断。
这种伪 JPQL 可能看起来像:
select t from Topic t left outer join t.posts p
order by "max(t.created , latest p.created if p exists)" desc
group by t.id
当然不行,因为我不知道怎么在这里写正确的order by子句。
有人可以给我一个提示吗?谢谢。
====================更新====================
感谢@Utsav SQL 示例。这就是有效的 JPQL:
select t
from Topic t
left outer join t.posts p
group by t.id
order by (case when p.id is null then t.created else max(p.created) end ) desc
我正面临这个问题:
Expression #3 of SELECT list is not in GROUP BY clause and contains nonaggregated column
'DBNAME.p.id' which is not functionally dependent on columns in GROUP BY clause;
this is incompatible with sql_mode=only_full_group_by
这似乎与 MySQL 5.7.x+ with OS/X 10.11 (Yosemite) 不兼容。我的工作解决方案在这里Getting this SQL Error: GROUP BY incompatible with sql_mode=only_full_group_by
修改my.cnf后重启MySQL就可以了。
【问题讨论】: