我有messages
表id, sender_id, receiver_id, sent_time, message
,如果我有user_id(可以是发件人和/或收件人),如何为每个对话者选择最后一条消息?我发现solution用于常见的MySQL查询,但这不适用于JPA查询/ CriteriaQuery。
在MySQL中,查询如下所示:
SELECT mm.* FROM messages mm
JOIN
(SELECT MAX(m.sent),u.id, m.id as idd FROM messages m
JOIN users u ON (m.sender_id=u.id OR m.receiver_id=u.id)
WHERE (m.sender_id=:uid AND m.receiver_id=u.id) OR (m.receiver_id=:uid AND m.sender_id=u.id) OR (m.receiver_id=:uid AND m.sender_id=:uid)
GROUP BY u.id) p2 ON mm.id=p2.idd
如何在HQL或CriteriaQuery中编写此查询("加入select max(m.sent),u.id ..."此部分)?