Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

joining tables while keeping the Null values

Tags:

sql

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:

? first_name  last_name
------------------------
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.

like image 206
Tam Avatar asked Mar 31 '10 15:03

Tam


People also ask

Do joins ignore NULL values?

If you attempt to join tables, and some of the columns contain null values, the null records will not be included in the resulting joined table.

Can you left join on NULL values?

The SQL LEFT JOIN returns all rows from the left table, even if there are no matches in the right table. This means that if the ON clause matches 0 (zero) records in the right table; the join will still return a row in the result, but with NULL in each column from the right table.

Does inner join work with NULL values?

When using left join, right join, full (outer) join, it is possible to return NULL value, while (inner) join, cross join will not return NUll value.

How do you deal with NULL values in a database table?

Handling SQL NULL values with Functions ISNULL(): The ISNULL() function takes two parameters and it enables us to replace NULL values with a specified value. The expression parameter indicates the expression which we want to check NULL values.


1 Answers

You need to put your condition into the ON clause of the LEFT JOIN.

Select
  u.first_name,
  u.last_name,
  n.status
From users u
Left Join networks n On (    ( n.user_id = 1 And n.friend_id = u.id )
                          Or ( n.friend_id = 1 And n.user_id = u.id )
Where u.id <> 1

This should return you all users (except for John Smith) and status friend if John Smith is either friend of this user, or this user is friend of John Smith.

like image 54
Peter Lang Avatar answered Sep 21 '22 17:09

Peter Lang