1

I have table messages

| id | user_id | recepient_id | message
| 1  |    1    |      2       | test1
| 2  |    1    |      2       | test2
| 3  |    2    |      1       | test3
| 4  |    3    |      1       | test4
| 5  |    3    |      2       | test5

I am user with id 1 and want to select rows where i am is a user_id or recepient_id (but only 1 row per user_id/recepient_id pair). It this example i want to select messages with ids - 2, 4 (or 1, 4 or 2, 3 or 2, 4. doesnt matter. just get uniq pairs for user_id/recepient_id)

How can i do it?

1 Answer 1

1
select distinct on (least(user_id, recipient_id), greatest(user_id, recipient_id))
    id, user_id, recipient_id, message
from the_table
where user_id = 1 or recipient_id = 1
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.