【问题标题】:JPA query order by comparison of local column and joined table column?通过比较本地列和连接表列的JPA查询顺序?
【发布时间】:2016-04-05 19:35:37
【问题描述】:

假设我有两个表:TopicPost

Topic@OneToMany Set<Post> posts 这意味着一个主题可能有零个或多个回复的帖子。 (并且Post 有一个@ManyToOne Topic topic 链接回Topic

TopicPost 都有一个 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就可以了。

【问题讨论】:

    标签: mysql sql jpa jpql


    【解决方案1】:

    编辑:按逻辑添加分组。

    我假设posts 表有一个引用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 小提琴演示

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

    【讨论】:

    • 嗨,如何按主题分组?演示:sqlfiddle.com/#!9/7cc6b/3。将列出重复的主题(因为它链接到 2 个帖子)。
    • 所以如果一个主题链接到多个帖子,您只需要最新的帖子创建日期对吗?
    • 是的,如果主题有帖子,它会抓取最新回复的帖子时间。如果主题没有帖子,它会检查自己的创建时间。按两次订购。
    • SQLFiddle 似乎没问题,但是在 mysql 中运行时,我面临 mysql 错误 1055: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 ... 不知道哪里出了问题。
    猜你喜欢
    • 2013-04-11
    • 1970-01-01
    • 2015-11-25
    • 2020-06-14
    • 1970-01-01
    • 2013-05-26
    • 2015-12-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多