MySQL/PHP - SELECT DISTINCT column based on another column with ORDER and LIMIT 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 |
+----+
Test:

SELECT CASE WHEN sender_id = 1 THEN receiver_id ELSE sender_id END user_id
FROM messages 
WHERE 1 IN (sender_id, receiver_id)
GROUP BY user_id
ORDER BY MAX(id) DESC LIMIT 3