all groups > sql server new users > february 2007 >
You're in the

sql server new users

group:

joining when they match AND DON'T?


joining when they match AND DON'T? HX
2/28/2007 1:20:43 PM
sql server new users:
I need to create a query that will pull in records from two tables when the
IDs match, and even if they don't. If there is no matching record, I need
to use the ID from table A and insert a NULL in the fields for table B.

Is this doable? If yes, how, and what is the name of this kind of query?

Table A
ID Field1
-------------
1 A
2 A
3 A

Table B
ID Field2
------------
1 B
3 B

Desired result:

ID Field1 Field2
------------------------
1 A B
2 A NULL
3 A B


Re: joining when they match AND DON'T? HX
2/28/2007 3:22:54 PM
Got it ... left outer join. Phew.

Thanks anyway.

[quoted text, click to view]

Re: joining when they match AND DON'T? AlterEgo
2/28/2007 5:17:02 PM
HX,

It is called an "outer join".

select a.ID, a.Field1, b.Field2
from TableA a
left outer join TableB b on a.ID= b.ID

-- Bill

[quoted text, click to view]

Re: joining when they match AND DON'T? Anthony Thomas
3/1/2007 7:11:04 PM
By the way, there is also a FULL OUTER JOIN when use would give you data
from both tables, and NULLs when no match was found in the other. You could
use an ISNULL function to make sure you provide an ID when one of them was
missing.

TABLE TableA:

ID FieldA
--- ----------
1 A1
2 A2
3 A3


TABLE TableB:

ID FieldB
--- ----------
1 B1
3 B3
4 B4

Then, for the query:

SELECT
ISNULL(a.ID, b.ID) AS ID
,a.FieldA
,b.FieldB

FROM
dbo.TableA AS a

FULL OUTER JOIN
dbo.TableB AS b
ON a.ID = b.ID

Would produce the following output:

ID FieldA FieldB
--- ---------- ----------
1 A1 B1
2 A2 NULL
3 A3 B3
4 NULL B4

Sincerely,


Anthony Thomas



--

[quoted text, click to view]

AddThis Social Bookmark Button