JPA,playframework,按分组前选择顺序

时间:2011-10-15 18:30:21

标签: java sql hibernate jpa

如何在“JPA”中编写查询 那将在GROUP BY之前订购?

例如:

select m from Message m where m.id = (
  select distinct m2.conversation_id
    from Message m2
   where m2.from = 100 or m2.to = 100
)
group by m.conversation_id order by m.date desc

我想要每个会话ID的最后(最近)消息。

1 个答案:

答案 0 :(得分:2)

简洁地说,你不能在GROUP BY之前放置ORDER BY; SQL需要GROUP BY之后的ORDER BY。

但是,您可以获得所需的结果 - 使用下面的冗长方法或使用不同的ORDER BY子句构造查询:

ORDER BY m.conversation_id, m.date DESC

在从数据库中提取数据的代码中,为每个返回的新会话ID选择第一行。

与往常一样,我分阶段构建查询。首先,找到涉及“用户ID 100”的每个会话ID的最新消息时间戳:

SELECT m2.conversation_id, MAX(m2.date) AS date
  FROM Message AS m2
 WHERE m2.from = 100 OR m2.to = 100
 GROUP BY m2.conversation_id

现在,将其与原始表连接以获取感兴趣的行:

SELECT m1.*
  FROM Message AS m1
  JOIN (SELECT m2.conversation_id, MAX(m2.date) AS date
          FROM Message AS m2
         WHERE m2.from = 100 OR m2.to = 100
         GROUP BY m2.conversation_id
       ) AS m3
    ON m1.conversation_id = m3.conversation_id AND m1.date = m3.date
 ORDER BY m1.date DESC;