mysql - 消息系统mysql,消息列表

标签 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)

最佳答案

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

关于mysql - 消息系统mysql,消息列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16586678/

相关文章:

MySQL:案例陈述问题

arrays - 如何找到其值具有最多元素的散列的键

mysql - 如何在 MYSQL 中通过另一列选择具有 MAX(列值)、PARTITION 的行?

mysql - 更新条目而不更新时间戳

mysql - 多人游戏历史数据库建模

mysql - Tank auth(CodeIgniter 库)中的 users 和 user_profiles 表有什么区别?

mysql - 提取 TEXT 字段中两个单词之间的文本

mysql - laravel 4 - 按查询加入最新结果

sorting - 有效地找到极值

jquery-ui - jquery UI slider 最小/最大值