1

I want to get values from two tables like in the following example:

Suppose we have this two tables:

TableA (with link to tableB):

Id | Id_TableB | Name
---------------------
1  |   1       |  Ralf
2  |   NULL    | Marta

TableB:

Id |  Color
---------------------
1  |  Blue
2  |  Red

I would like to get values for Color if there is a link, NULL otherwise:

Result:

Id |   Name | Color
-----------------------------
1  |    Ralf| Blue
2  |   Marta| NULL

Any ideas on how to solve this?

Daniel
  • 20,420
  • 10
  • 92
  • 149

4 Answers4

5

You need a left outer join .

SELECT t1.Id, t1.Name, t2.Color 
from TableA t1 left outer join TableB t2 
on t1.Id_TableB = t2.Id;

Please check the link that I have provided above. Its a simplified tutorial

reggie
  • 13,313
  • 13
  • 41
  • 57
1

You need to use a LEFT OUTER JOIN, which includes rows even when there are NULLs. Something like this:

SELECT * 
FROM   TableA a
LEFT OUTER JOIN TableB b on a.ID_TableB = b.ID

More info here:

http://msdn.microsoft.com/en-us/library/ms187518.aspx

Hope this helps,

John

JohnD
  • 14,327
  • 4
  • 40
  • 53
1
select
    a.Id,
    a.Name,
    b.Color
from
    a
    left outer join
        b
    on
        a.Id_TableB = b.Id
group by
    b.Id

The group by b.Id is necessary if you have a one-to-many relationship a->b.

Björn
  • 29,019
  • 9
  • 65
  • 81
-1

just you have to use outer join for this....

select a.id,a.Name, b.Color from tableB as b 
   left join tableA as a on b.Id = a.id_tableB

and for this you can use in condition as well you can try below query--

select a.id,a.Name, b.Color from tableB as b,tableA as a on b.Id(+) = a.id_tableB
pratik garg
  • 3,282
  • 1
  • 17
  • 21
  • 1
    SQL Server supports LEFT JOIN, there's [no need](http://stackoverflow.com/questions/894490/sql-left-join-vs-multiple-tables-on-from-line/894659#894659) to recommend the outdated implicit join syntax (especially when it is Oracle's). – Andriy M Jul 12 '11 at 12:13
  • i was just telling the way and possibilities exist for this question..... if you know then it is good if you know about left outer join but if not you can use second option as well .... anyways i don't know it is outdated.. thanks for update me .. although it is still using by many big bank's running projects – pratik garg Jul 12 '11 at 14:20
  • I realise that there might still be many people quite familiar with the older syntax, and probably even more projects still using it. However, I don't see a point in recommending an *outdated* standard to a person who apparently is *new* to the concept. And, again, the syntax in your second snippet is Oracle's. SQL Server's legacy syntax uses the [`*=`](http://msdn.microsoft.com/en-us/library/aa213228%28v=sql.80%29.aspx) operator for left outer join. And it is not supported by the current version of SQL Server (SQL Server 2008 R2) unless the compatibility level is set to 80 (SQL Server 2000). – Andriy M Jul 12 '11 at 14:43