joining tables while keeping the Null values

Posted by Tam on Stack Overflow See other posts from Stack Overflow or by Tam
Published on 2010-03-31T15:28:52Z Indexed on 2010/03/31 15:33 UTC
Read the original article Hit count: 459

Filed under:

I have two tables:

Users: ID, first_name, last_name

Networks: user_id, friend_id, status

I want to select all values from the users table but I want to display the status of specific user (say with id=2) while keeping the other ones as NULL. For instance: If I have users:

1 John Smith
2 Tom  Summers
3 Amy  Wilson

And in networks:

user_id   friend_id   status
2         1           friends

I want to do search for John Smith for all other users so I want to get:

id first_name  last_name   status
2  Tom         Summers     friends  
3  Amy         Wilson      NULL

I tried doing LEFT JOIN and then WHERE statement but it didn't work because it excluded the rows that have relations with other users but not this user.

I can do this using UNION statement but I was wondering if it's at all possible to do it without UNION.

© Stack Overflow or respective owner

Related posts about sql