JPA 通过比较本地列和加入的 table 列来查询顺序?

JPA query order by comparison of local column and joined table column?

假设我有两个表:TopicPost

Topic@OneToMany Set<Post> posts,这意味着一个主题可能有零个或多个回复 post。 (并且 Post 有一个 @ManyToOne Topic topic link 回到 Topic

TopicPost 都有一个 created 列,存储时间戳。

我想得到一个topic按最近回复post时间排序的列表,如果一个topic没有post回复,它会从topic的创建时间来判断.

这样的伪 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+ 与 OS/X 10.11 (Yosemite) 不兼容。我的工作解决方案在这里 Getting this SQL Error: GROUP BY incompatible with sql_mode=only_full_group_by

修改my.cnf后重启MySQL就可以了

编辑:按逻辑添加分组。

我假设 posts table 有一个引用 topic.idtid 列。

select t.id,
    case when p.id is null 
        then t.created
        else max(p.created) 
    end 
as derived_max_time
From topic t
left join posts p
on t.id=p.tid
group by t.id
order by derived_max_time desc

请在此处查看更新的 MYSQL fiddle 演示

http://sqlfiddle.com/#!9/abbfb/8