Joining two tables with a null foreign key?

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

if FK_TypeID is NULL for a specific string, TypeName also NULL. I'm not sure how to do this?

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

My current status looks like this and just skips NULL FK_TypeID rows

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

Help will be greatly appreciated!

+6
source share
2 answers

You just need to use LEFT JOIN

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

If no match for Actions is found, associate it with Type , then all columns in Type will be NULL .

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

+19
source

Use EXTERNAL EVENTS

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

Source: https://habr.com/ru/post/913173/


All Articles