消息系统的mysql查询

时间:2013-02-04 22:53:12

标签: mysql sql

我正在开发邮件系统,并且在写下查询(MYSQL)时遇到了麻烦。 简而言之,查询应该为每个对话用户返回一个最后一条消息的数组给用户。

CREATE TABLE 'tbl_message'('id' int(10) AUTO_INCREMENT,
  'from_user' int(10),
  'to_user' int(10),
  'reply_to' int(10),
  'subject',
  'body' text,
  'status' tinyint(3),
  'deleted_from_sender' tinyint(3),
  'deleted_from_recipient' tinyint(3)',
  'created_on' datetime,

我写了查询:

SELECT * FROM tbl_message s1 WHERE s1.created_on IN (
   SELECT MAX(s2.created_on)
      FROM tbl_message s2 WHERE s1.from_user=".$userID." OR s2.to_user=".$userID."
      GROUP BY s2.from_user, s2.to_user) 
       AND status = 0";

这很好但是从from_user和to_user给我最后两条消息,而不是两条消息中的最后一封消息。因为GROUP BY当然,现在的问题是如何在子查询中找到max created_on(实际上是mysql datestamp)?或者任何其他解决方案将不胜感激。 感谢任何帮助或建议。

经过2天挖掘stackoverflow和mysql手册希望得到DB prof :)的帮助

UPD: 一些数据,例如

+----+-------+--------+--------+---------------------+--------+---------+
| id | from_user | to_user | subject      | created_on          | status |
+----+-------+--------+--------+---------------------+--------+---------+
|  1 |   68      |   128   | somesubject1 | 2013-07-01 21:31:29 |      0 |
+----+-------+--------+--------+---------------------+--------+---------+
|  2 |    128    |   68    | somesubject2 | 2013-07-01 21:41:29 |      0 |
+----+-------+--------+--------+---------------------+--------+---------+
|  3 |    128    |   68    | somesubject3 | 2013-07-01 21:51:29 |      0 |
+----+-------+--------+--------+---------------------+--------+---------+
|  4 |    68     |   226   | somesubject4 | 2013-07-01 22:01:29 |      0 |
+----+-------+--------+--------+---------------------+--------+---------+

查询输出

|  3 |    128    |   68    | somesubject3 | 2013-07-01 21:51:29 |      0 |
+----+-------+--------+--------+---------------------+--------+---------+
|  4 |    68     |   226   | somesubject4 | 2013-07-01 22:01:29 |      0 |

1 个答案:

答案 0 :(得分:0)

您可以使用此查询获取两个用户之间的最大created_on日期:

SELECT
  LEAST(from_user, to_user) user1,
  GREATEST(from_user, to_user) user2,
  MAX(created_on) max_created_on
FROM
  tbl_message
GROUP BY
  LEAST(from_user, to_user),
  GREATEST(from_user, to_user)

您要查找的查询可能就是:

SELECT t.*
FROM
  tbl_message t INNER JOIN (
    SELECT
      LEAST(from_user, to_user) user1,
      GREATEST(from_user, to_user) user2,
      MAX(created_on) max_created_on
    FROM
      tbl_message
    WHERE from_user=68 or to_user=68
    GROUP BY
      LEAST(from_user, to_user),
      GREATEST(from_user, to_user)) M
  on t.created_on = M.max_created_on
     AND LEAST(t.from_user, t.to_user)=user1
     AND GREATEST(t.from_user, t.to_user)=user2

查看两个查询here