Had a question..
| a_id | name | r_id | message | date
_____________________________________________
| 1 | bob | 77 | bob here | 1-jan
| 1 | bob | 77 | bob here again | 2-jan
| 2 | jack | 77 | jack here. | 2-jan
| 1 | bob | 79 | in another room| 3-feb
| 3 | gill | 79 | gill here | 4-feb
These are basically accounts (a_id)
chatting inside different rooms (r_id
)
I’m trying to find the last chat message for every room that jack a_id = 2
is chatting in.
What i’ve tried so far is using distinct on (r_id) ... ORDER BY r_id, date DESC
.
But this incorrectly gives me the last message in every room instead of only giving the last message in everyroom that jack belongs to.
| 2 | jack | 77 | jack here. | 2-jan
| 3 | gill | 79 | gill here | 4-feb
Is this a partition
problem instead distinct on?
2
Answers
I would suggest :
r_id
with aGROUP BY
clausea_id = 2
is included with aHAVING
clause which aggregates thea_id
of each group :HAVING array_agg(a_id) @> array[2]
ORDER BY date DESC
and selecting the first element of the array :(array_agg(t.*))[1]
json_populate_record
functionThe full query is :
and the result is :
see dbfiddle
For last message in every chat room simply would be:
Fiddle https://www.db-fiddle.com/f/keCReoaXg2eScrhFetEq1b/0
Or seeing messages
Fiddle https://www.db-fiddle.com/f/keCReoaXg2eScrhFetEq1b/1
Though all this complication could by avoided with a primary key on your table.