I have a table named messages that is as follows:
+-----+-----------+-------------+-----+
| id | sender_id | receiver_id | ... |
+-----+-----------+-------------+-----+
| . | . | . | ... |
| . | . | . | ... |
| 120 | 19 | 11 | ... |
| 121 | 1 | 3 | ... |
| 122 | 9 | 18 | ... |
| 123 | 2 | 1 | ... |
| 124 | 1 | 24 | ... |
| 125 | 3 | 1 | ... |
| 126 | 7 | 5 | ... |
| 127 | 24 | 1 | ... |
| 128 | 25 | 1 | ... |
| 129 | 1 | 25 | ... |
| 130 | 7 | 3 | ... |
| 131 | 3 | 5 | ... |
+-----+-----------+-------------+-----+
How can I select the last 3 unique users that have communicated with User 1? In other words, how can I select:
- distinct sender_ids whose receiver_id is 1 or distinct receiver_ids whose sender_id is 1
- in descending order and limited to 3?
The result would look like this:
+-----+-----------+-------------+-----+
| id | sender_id | receiver_id | ... |
+-----+-----------+-------------+-----+
| 129 | 1 | 25 | ... |
| 127 | 24 | 1 | ... |
| 125 | 3 | 1 | ... |
+-----+-----------+-------------+-----+
or simply:
+----+
| 25 |
| 24 |
| 3 |
+----+