1

I have a scenario where I have a users table where users are connections to each other based on the connections table. The connections table has a user_id1 field and a user_id2 field.

I want to get the connections for a specific user:

select id, user_id1, user_id2 
from connections 
where user_id1 = 1 or user_id2 = 1

But the user_id's of the connections are separated into two columns. How can I get the connections of the specific user in one one column.

I've tried this but it didn't work:

select user_id1 or user_id2 
from 
    (select id, user_id1, user_id2 
     from connections 
     where user_id1 = 1 or user_id2 = 1) as con 
where user_id1 != 1 and user_id2 != 1
1
  • Tag your question with the database you are using. Commented Apr 4, 2021 at 11:39

1 Answer 1

3

Use a CASE expression:

SELECT CASE user_id1
         WHEN 1 then user_id2 
         ELSE user_id1
       END AS user_id
FROM connections 
WHERE 1 IN (user_id1, user_id2)
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.