2012-10-05 100 views
2

我有一个带有表MESSAGE的数据库,它包含我所有的消息。 我需要找到所有最后的对话信息。SQL嵌套查询问题

表包含以下字段: ID(INT) 从(INT) ,与(int) 日期(日期) 消息(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" 

我希望这是清楚我的意思......我 已经可以发现我有一个交谈的用户,这个查询:

在该示例中用户具有标识= 47

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

谢谢!

+0

最后一个线程(发件人 - 收件人)还是最后一个发件人或收件人? – amphibient

+0

最后在线程中,所以有点像在手机上一样,您可以在短信收件箱中看到所有对话,并查看最后一条消息,发送它或发送它并不重要 – dumazy

+0

什么我会做的是有一个列(这可能看起来违反规范化,但会提高性能)threadID,这将是,然后为了简单分组。所以在上面的例子中,相应的线程ID将是:1.3(对于1-> 3),1.3(对于3-> 1),1.2(对于1-> 2),3.5(对于3-> 5) – amphibient

回答

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 

这个us通过id找到对话中的最后一条记录。然后它回来收到消息。

2

男人,这真的很粗糙,看起来很丑陋,但我认为这是一个体面的起点......让用户进入一个“虚拟化”的单一表格,获得最大信息日期,然后每个用户ID为那些,并加入原始消息表。这至少是希望! :)请注意,“from”值几乎肯定是一个保留的SQL关键字,所以实际上它需要来自fromID或类似的东西,但无论如何...有了这样的警告......

* 编辑:测试前面的例子,这是不完全正确的,但每个SQLFiddle这一个工程在http://sqlfiddle.com/#!3/3f586/2

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