Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

joining two tables with nullable foreign key?

I created two tables below, and FK_TypeID is nullable in this case. I want to write a query returning me the join of two tables.

if FK_TypeID is NULL for a certain row, the TypeName is also NULL. I am not sure how to go about creating such join statement?

[Actions]
ActionsID
Date
Message
FK_TypeID //links to the table below

[Type]
TypeID
TypeName

My current statment looks like this and it simply skips NULL FK_TypeID rows

SELECT        *
FROM            Actions 
INNER JOIN      TypeName ON Actions.FK_TypeID = [Type].TypeID

Help would be greatly appreciated!

like image 429
Bonk Avatar asked Apr 13 '12 21:04

Bonk


People also ask

Can we join two tables using foreign key?

A table must have exactly one primary key to qualify as relational, but that key can be composed of multiple columns. A foreign key, by contrast, is one or more fields or columns that corresponds to the primary key of another table. Foreign keys are what make it possible to join tables to each other.

Can you have a foreign key on a nullable field?

A table can have many foreign keys. A foreign key is nullable if any part is nullable. A foreign key value is null if any part is null.

Can we join two tables with NULL values?

Null values in tables or views being joined never match each other. Since bit columns do not permit null values, a value of 0 appears in an outer join when there is no match for a bit column in the inner table. The result of a join of null with any other value is null.

Do JOINs work on nulls?

As we have seen from the above examples joining NULL values does not work. Even though you have two NULL values SQL Server does not treat these as the same value. Internally a value of NULL is an unknown value and therefore SQL Server does not equate an unknown value being equal to another unknown value.


2 Answers

You just need to use a LEFT JOIN

SELECT Actions.Date, Actions.Message, Type.TypeName
FROM Actions
    LEFT JOIN Type 
        ON Type.TypeID = Actions.FK_TypeID

If a match to Actions is not found to tie it with Type, then all columns in Type will be NULL.

Here is a good graphical visualization of the different types of joins in SQL

like image 166
Justin Pihony Avatar answered Oct 20 '22 23:10

Justin Pihony


Use an OUTER JOIN

SELECT Actions.Date, Actions.Message, Type.TypeName 
FROM   Actions LEFT OUTER JOIN 
           Type ON Type.TypeID = Actions.FK_TypeID 
like image 42
AFIS Avatar answered Oct 21 '22 00:10

AFIS