Monday, February 21, 2011

MySQL, if a value is in one of two columns, return the value from the other one

Hi,

This might be an easy one, but I'm not really experienced with sql.

I have a table with two user_id columns, user1 and user2. This table contains some compared values between the two users.

I want to send in an user id, and return all the id's from the other user when the sent user is either user1 or user2.

I guess some sort of if test would do the trick, but I don't know how to do this in SQL.

Cheers

From stackoverflow
  • You can do:

    SELECT user1 FROM TAB WHERE user2=id
    UNION ALL
    SELECT user2 FROM TAB WHERE user1=id
    
  • One way to do this is:

    SELECT IF(user1 = ID, user2, user1) AS other_user FROM table WHERE user1 = ID OR user2 = ID
    
  • codaddict's solution would work i would however go with the following:

    select if(user1 = userparam, user2, user1) as user
    from table
    where user1 = userparam or user2 = userparam
    

    EDIT: Replaced the case with an if funtion.

0 comments:

Post a Comment