显示我收到消息的十个第一个联系人

时间:2011-02-28 18:37:56

标签: java mysql sql

我想创建一个Sql语句,显示我收到的十个第一个联系人以及他们最新发送的消息和时间。表格列为messageId, messageBody, fromUser, toUser, timeStamp,表格称为messages。数据库是Mysql,Java是语言。但是我想在一个单独的sql语句中发生这种情况。

4 个答案:

答案 0 :(得分:0)

您可以使用group by查找每个联系人的最新消息。然后,您可以加入回消息表以检索消息正文:

select  LastTen.Contact
,       LastTen.LastMessageDate
,       msg.messageBody
from    (
        select  fromUser as Contact
        ,       max(timeStamp) as LastMessageDate
        from    YourTable
        where   toUser = 'YourName'
        group by
                fromUser
        order by
                max(timeStamp) desc
        limit 10
        ) LastTen
join    YourTable msg
on      msg.fromUser = lastTen.Contact
        msg.timeStamp = lastTen.LastMessageDate

答案 1 :(得分:0)

我正在将“显示十个第一次联系人”解释为提交消息的前10个人。

Select M2.fromUser
    , LastMessage.messageBody
    , LastMessage.timeStamp
From    (
        Select M1.fromUser
            , Min(M1.timeStamp) As FirstMessage
            , Max(M1.messageId) As LastMessageId
        From messages As M1
        Where M1.toUser = 'my username'
        Group By M1.fromUser
        Order By Min(M1.timeStamp) Asc
        Limit 10
        ) As M2
    Join messages As LastMessage
        On LastMessage.messageId = M2.LastMessageId

答案 2 :(得分:0)

这样的事可能有用:

SELECT fromUser, messageBody, timeStamp
FROM   (SELECT DISTINCT fromUser FROM messages ORDER BY timeStamp LIMIT 10) AS m1
       LEFT JOIN messages
         ON(fromUser)
ORDER BY timeStamp DESC LIMIT 1

答案 3 :(得分:-1)

SELECT fromUser, timeStamp, messageBody FROM messages ORDER BY timeStamp LIMIT 10