我有一张桌子:
messages( id, owner, author, message, chat_id, message_date)
我希望获得最后留言信息的聊天列表。 我怎么能这样做?
我试过
SELECT MAX(message_date), id, owner, author, message, chat_id
FROM messages WHERE owner = ? GROUP BY chat_id
但它没有用。
答案 0 :(得分:0)
您可以使用row_number
获取最新消息以及相应的日期。
select message_date, id, owner, author, message, chat_id
from (
SELECT row_number() over(partition by chat_id order by message_date desc) as rn,
message_date, id, owner, author, message, chat_id
FROM messages WHERE owner = ? ) t
where rn = 1
答案 1 :(得分:0)
你想要每个chat_id,但只有最新的条目,如果有几条消息?
SELECT message_date, id, owner, author, message, chat_id
FROM messages m1
WHERE owner = ?
where not exists (select 1 from messages m2
where m2.chat_id = m1.chat_id
and m2.message_date > m1.message_date)
仅当相同的聊天没有后续条目时才返回一行。