I am trying to select the most recent record between 2 users based on a to_number and a from_number and created date/time.
Once the record is found, display the message and time stamp. As long as either the to_number or from_number have the same pairing, then that is the message I want to display.
I’m really getting stuck on finding unique to/from OR from/to records with the same number combinations AND that haven’t been listed before.
My data:
Messages table:
"id","to_number","from_number","message","created_at","dm_user_id"
"1","7325551212","5705551234","new update","2011-12-17T11:26:33-05:00","1"
"2","5705551234","3015551212","next update","2011-12-17T11:26:53-05:00","1"
"3","6095559876","4695551212","trying messages.","2011-12-19T19:20:47-05:00","2"
"4","5705551234","4155551212","did i get this?","2011-12-19T20:04:40-05:00","1"
"5","9075551212","5705551234","Where did this go?","2011-12-19T20:05:51-05:00","1"
"6","9075551212","5705551234","testing","2011-12-19T20:12:53-05:00","1"
"7","3015551212","5705551234","Are you here ","2011-12-19T20:13:34-05:00","1"
"8","6175554567","4695551212","test from app","2011-12-19T22:51:32-05:00","2"
From the above data, I only want the following records, listed newest to oldest.
NOTE: Not all records will be returned because there are duplicate to/from combinations. For example, id 2 and id 7 are messages between the same 2 numbers. Only the most recent will be returned, id 7.
Another example is id 5 and id 6 – they are both to/from the same numbers so only the most recent is returned, id 6.:
for dm_user_id=1
"3015551212", "Hello", "2011-12-19T20:13:34-05:00" # id 7
"9075551212", "testing", "2011-12-19T20:12:53-05:00" # id 6
"4155551212", "did i get this?", "2011-12-19T20:04:40-05:00" # id 4
"7325551212", "new update", "2011-12-17T11:26:33-05:00" # id 1
for dm_user_id=2
"6175554567", "test from app", "2011-12-19T22:51:32-05:00" # id 8
"6095559876", "trying messages.", "2011-12-19T19:20:47-05:00" # id 3
I’m trying different combinations of GROUP BY and DISTINCT, but not getting the results I’m looking for.
select * from messages where dm_user_id = 1
group by to_number, from_number
select * from (
select DISTINCT to_number, from_number dm_user_id
from messages) where dm_user_id = 1
This is a common question, basically you want the most recent message from each number, either TO or FROM, but you don’t want duplicates. You may find something useful in this category greatest-n-per-group