Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sql join return null if value not found

Tags:

sql

join

I have table with countries, resorts and photos for resorts. Each photo may be marked as title for album. I want to select joined dataset with country id and name, resort id and name and photo only if it marked as title, otherwise - null.

I tried to do following:

select
    s.id as c_id,
    s.name as c_name,
    t.id as r_id,
    t.name as r_name,
    p.thumbnail as image,
    p.description as desc,
    p.is_title
from dbo.countries s
join dbo.resorts t on t.state=s.inc
left outer join dbo.resorts_photo p on p.resort_id=t.inc
where s.inc=@country_id

And I've got list of all photos - titled and not. If I adding filering by is_title filed ( 'and p.is_title=1') all resorts which hasn't titled photo will be droppped off from result datase - not what I want.

I just want to get something like (see last row):

c_id c_name     r_id  r_name    image   desc  is_title
2    Australia  17    Adelaida  0xXXXX  NULL  1
2    Australia  178   BB Rief   0xXXXX  blah  1
2    Australia  160   Brum      NULL    NULL  NULL
like image 469
Alex G.P. Avatar asked Jan 31 '12 12:01

Alex G.P.


People also ask

How do you handle NULL in join condition?

The result of a join of null with any other value is null. Because null values represent unknown or inapplicable values, Transact-SQL has no basis to match one unknown value to another. You can detect the presence of null values in a column from one of the tables being joined only by using an outer join.

Does join return NULL?

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. The following example is the difference between these joins, please refer to: --join.

How do I get a blank NULL instead of SQL?

There are two ways to replace NULL with blank values in SQL Server, function ISNULL(), and COALESCE(). Both functions replace the value you provide when the argument is NULL like ISNULL(column, '') will return empty String if the column value is NULL.

Can SQL query return NULL?

The IS NULL condition is used in SQL to test for a NULL value. It returns TRUE if a NULL value is found, otherwise it returns FALSE. It can be used in a SELECT, INSERT, UPDATE, or DELETE statement. Your browser can't play this video.


1 Answers

Include the extra predicate(s) in your JOIN condition rather than the WHERE clause so that they do not cause the entire row to be removed:

LEFT OUTER JOIN dbo.resorts_photo AS p
ON p.resort_id = t.inc
AND p.is_title = 1
like image 50
Mark Byers Avatar answered Oct 01 '22 23:10

Mark Byers