gpt4 book ai didi

mysql - 选择每个线程的最新消息

转载 作者:行者123 更新时间:2023-11-29 04:37:20 24 4
gpt4 key购买 nike

我有一个包含以下列的表(消息)

message_id (pk), thread_id, message_body, date_posted, posted_by,....

如何根据发布日期降序选择每个线程的最新消息?

样本表

-------------------------------------------------
message_id | thread_id | body | date_posted
-------------------------------------------------
1 | 1 | ... | 2016-06-03
-------------------------------------------------
2 | 1 | ... | 2016-06-04
-------------------------------------------------
3 | 2 | ... | 2016-06-05
-------------------------------------------------
4 | 1 | ... | 2016-06-06
-------------------------------------------------
5 | 2 | ... | 2016-06-07
-------------------------------------------------
6 | 3 | ... | 2016-06-08
-------------------------------------------------
7 | 2 | ... | 2016-06-09
-------------------------------------------------

预期结果

-------------------------------------------------
message_id | thread_id | body | date_posted
-------------------------------------------------
7 | 2 | ... | 2016-06-09
-------------------------------------------------
6 | 3 | ... | 2016-06-08
-------------------------------------------------
4 | 1 | ... | 2016-06-06
-------------------------------------------------

最佳答案

试试这个;)

select t1.*
from messages t1
inner join (
select max(date_posted) as date_posted, thread_id
from messages
group by thread_id
) t2 on t2.thread_id = t1.thread_id and t2.date_posted = t1.date_posted
order by t1.date_posted

或者你可以使用 in :

select *
from messages
where (date_posted, thread_id) in (
select max(date_posted) as date_posted, thread_id
from messages
group by thread_id
)
order by date_posted

SQLFiddle DEMO HERE

关于mysql - 选择每个线程的最新消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38114867/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com