I’m developing messaging system and have a trouble writing down the query(MYSQL).
In the nutshell query should return an array of one last messages for each conversation user to user.
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,
I wrote query:
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";
That works fine but give me 2 last messages from from_user and to_user, instead of 1 last message from both. That because of GROUP BY of course, now the question is how I could find the max created_on(actually mysql datestamp) in subquery? Or any other solution will be appreciated.
Appreciate any help or advice.
After 2 days digging stackoverflow and mysql manuals hope for help from DB prof:)
UPD:
some data for example
+----+-------+--------+--------+---------------------+--------+---------+
| 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 |
+----+-------+--------+--------+---------------------+--------+---------+
output of query
| 3 | 128 | 68 | somesubject3 | 2013-07-01 21:51:29 | 0 |
+----+-------+--------+--------+---------------------+--------+---------+
| 4 | 68 | 226 | somesubject4 | 2013-07-01 22:01:29 | 0 |
You could use this query to get the maximum created_on date between two users:
and the query you are looking for is probably this:
See fiddle with both queries here.