I have two tables:
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.
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.
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.
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.
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With