1

这应该很简单,但是我坚持下去。

当我做查询

SELECT * FROM `inbox` where toid=4 or fromid=4 order by time desc

,我得到:

id  toid    fromid  message           time
23  48101   4   hello call me     12/23/2011 12:27
6   34584   4   hi there      12/22/2011 15:42
5   34584   4   how are you   12/22/2011 14:08
4   34584   4   say hello     12/22/2011 14:07
3   34584   4   whats up      12/22/2011 14:07
2   4   34584   nice picture      11/24/2010 0:00
1   4   2   this is very interesting!   12/23/2008 0:00

现在,我需要将用户 4 和其他用户之间的对话分组到最后一条消息的一行(就像 facebook 消息一样)。

有人知道最好的方法吗?

谢谢!

4

1 回答 1

4

SQL小提琴

select i.id, toid, fromid, message, `time`
from
    inbox i
    inner join (
        select max(id) as id
        from inbox
        where toid = 4 or fromid = 4
        group by greatest(toid, fromid), least(toid, fromid)
    ) s on i.id = s.id
于 2012-10-18T11:21:39.237 回答