每个线程选择最新消息

时间:2016-06-30 05:47:26

标签: mysql sql

我有一个表格(消息),其中包含以下列

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
-------------------------------------------------

4 个答案:

答案 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

SQLFiddle DEMO HERE

答案 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)

通过以降序为基础给出基于thread_id和date_posted的行号,只是另一个视角。

<强>查询

{{1}}

SQL Fiddle Demo