我正在开发消息传递系统并且在写下查询(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 的 2 条最后一条消息,而不是来自两者的 1 条最后一条消息。那当然是因为 GROUP BY,现在的问题是我如何在子查询中找到 max created_on(实际上是 mysql 日期戳)?或任何其他解决方案将不胜感激。感谢任何帮助或建议。
经过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 |