I have a messages table. As a side note all ids are UUIDs not INTs
messages
- id
- from_id
- to_id
- text
- inserted_at
I want to retrieve the last message that was either sent or received by user x with every other user.
So given a table with this data
--------------------------------------------------
| id | from_id | to_id | text | inserted_at |
---------------------------------------------------
| 1 | 1 | 2 | hello | 2020-01-01 |
| 2 | 2 | 1 | sup | 2020-01-02 |
| 3 | 1 | 3 | hello | 2020-01-01 |
| 4 | 2 | 3 | howdy | 2020-01-01 |
I want to retrieve the messages for user 1.
Pseudo SQL
SELECT DISTINCT OR (from_id, to_id) text, inserted_at
FROM messages
WHERE from_id = 1 OR to_id = 1
ORDER BY inserted_at;
The result should be:
--------------------------------------------------
| id | from_id | to_id | text | inserted_at |
---------------------------------------------------
| 2 | 2 | 1 | sup | 2020-01-02 |
| 3 | 1 | 3 | hello | 2020-01-01 |