假设我有两个表: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 +与OS / X 10.11(Yosemite)不兼容。我的工作解决方案在Getting this SQL Error: GROUP BY incompatible with sql_mode=only_full_group_by
修改my.cnf
并重启MySQL后,就可以了。
答案 0 :(得分:1)
编辑:按逻辑添加组。
我假设posts
表有tid
列引用topic.id
。
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小提琴演示