2013-05-16 131 views
0

我正在制作一个类似facebook的消息系统。消息系统mysql,消息列表

我有两个表:

messages => 
    m_id (message id) 
    t_id (thread id) 
    author_id (id of user that wrote the message) 
    text (Text for the message) 
    date (date) 
    time (time) 

thread_recipients => 
    t_id (thread_id) 
    user_id (id of the user that will belong to this thread) 
    read (Flag to tell if there are any unread messages) 

所以我基本上要为获得线程(对话),一个用户的部分名单。在该列表中,我想选择在线程中发布的最后一条消息的文本,日期和时间。

我已经做了sqlfiddle: http://sqlfiddle.com/#!2/a3d9b/2

所以基本上我想这个查询只返回最后一排,因为它具有最高的消息ID。

如果可以在没有子查询的情况下完成,那就太棒了。如果没有,那么我只好住在一起(:

编辑: 我想出如何使用子查询做到这一点,但在这里我最大的担忧是表现我非常喜欢做的事。 。另一种方式,如果可能的

SELECT r.t_id, m.author_id, left(m.text, 50) 
FROM 
messages m, 
thread_recipients r 
WHERE 
r.user_id = 16 and 
r.t_id = m.t_id and 
m.m_id = (SELECT MAX(mm.m_id) FROM messages mm WHERE mm.t_id = m.t_id) 

回答

0

试试这个

SELECT r.t_id, m.author_id, left(m.text, 50) 
FROM messages m, thread_recipients r 
WHERE 
r.user_id = 16 and r.t_id = m.t_id 
GROUP BY m.m_id 
ORDER BY m.m_id DESC 
LIMIT 1 

我已更新您的sqlfiddle

+0

刚刚尝试过,并将用户16添加到线程2并删除了限制。这返回了全部6条消息。我需要选择用户所在的所有线程,但只能从最新的线程获取文本。但我喜欢这种方法,它可以工作吗? – jah