消息系统mysql,消息列表

消息系统mysql,消息列表,mysql,max,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 (i

我正在制作一个类似于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)
所以我基本上想要的是得到一个用户参与的线程(对话)列表。在该列表中,我想选择在线程中发布的最后一条消息的文本、日期和时间

我做了一把小提琴:

所以基本上我希望这个查询只返回最后一行,因为它有最高的消息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)
看看这个: 我想这就是你需要的。

试试这个

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

我已经更新了你的

我确实知道max,但我的问题是如何实现它,最好是不使用子查询。只是尝试了一下,将用户16添加到线程2并删除了限制。这返回了所有6条消息。我需要选择用户所在的所有线程,但只能从最新的线程中获取文本。但是我喜欢这种方法,不是吗工作