2

我有一个带有 MESSAGE 表的数据库,它包含我的所有消息。我需要找到所有最后的对话消息。

该表包含以下字段: Id (int) From (int) To (int) Date (date) Message (varchar)

我需要找到一个返回所有最后消息的查询。例如:

1 -> 3 : This is a first message; yesterday
3 -> 1 : This is the last one; today
1 -> 2 : Another message with 1 and 2; some time
3 -> 5 : Some message i don't need; some time

我需要找到:

"3 -> 1 : This is the last one; today"
"1 -> 2 : Another message with 1 and 2; some time"

我希望我的意思很清楚......我已经可以通过以下查询找到与我交谈的用户:

在此示例中,用户的 Id = 47

select distinct m.To from MESSAGE m Where m.From = 47 union select distinct m2.from From MESSAGE m2 where m2.To = 47

谢谢!

4

2 回答 2

2

伙计,这真的很粗糙而且看起来很丑陋,但我认为这是一个不错的起点......将 from 和 to 用户放入一个“虚拟化”单表,获取其中一个/两个的最大消息日期,然后最大化那些每个用户 ID,并加入原始消息表。这至少是希望!:) 请注意,“from”值几乎可以肯定是一个保留的 SQL 关键字,所以实际上它需要是 fromID 或类似的东西,但无论如何......有这个警告......

*编辑:测试了前面的例子,这不是很正确,但是这个在http://sqlfiddle.com/#!3/3f586/2上的每个 SQLFiddle 都有效

select distinct fromid, toid, message
  from messages
  join (select distinct max(msgDate) msgdate, userid from
                    (select max(messageDate) msgdate, fromID userid
                       from messages
                      group by fromID
                      union 
                     select max(messageDate), toID userid
                       from messages
                      group by toID) as j group by userid ) as x
   on (messages.fromID=x.userid
       or messages.toID=x.userid)
  and messages.messageDate=x.msgdate
于 2012-10-05T14:32:11.590 回答
2

我认为这会做你想要的,假设 id 可以用来定义“最后一条消息”:

select m.*
from message m join
     (select least(from, to) as p1, greatest(from, to) as p2, max(id) as maxid
      from message m
      group by least(from, to), greatest(from, to)
     ) mmax
     on m.id = mmax.maxid

这使用 id 来查找对话中的最后一条记录。然后它重新加入以获取消息。

于 2012-10-05T15:21:41.317 回答