我有一个表格(消息),其中包含以下列
message_id( pk ),thread_id,message_body,date_posted,posted_by,....
如何根据date_posted选择每个线程的最新消息,结果按降序排列?
样本表
-------------------------------------------------
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
-------------------------------------------------
答案 0 :(得分:3)
试试这个;)
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
答案 1 :(得分:1)
你可以这样做
SELECT thread_id,message FROM (Select * from messages ORDER BY thread_id,latestDate DESC) r group by thread_id;
答案 2 :(得分:0)
试试这个
SELECT * FROM messages GROUP BY thread_id ORDER BY date_posted DESC;
答案 3 :(得分:0)