消息系统mysql,消息列表

时间:2013-05-16 11:52:35

标签: mysql max

我正在制作一个类似于facebook的消息系统。

我有两张桌子:

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)

2 个答案:

答案 0 :(得分:0)

看看这个:http://www.techonthenet.com/sql/max.php 我认为这就是你所需要的。

答案 1 :(得分: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