Search code examples
c#sqlif-statementjoininner-join

SQL join 2 tables with condition taking some default NULL values due to condition


I am taking some data from tables using join,

    SELECT da.aName AS aName FROM dbo.bTable 
INNER JOIN aTable da ON dbo.bTable.nameType = da.ID"

This select works. But if nameType is some new number which is not in da.ID, then this row is not shown at all. what I want is to join these to tables, but if aTable does not contain such number at all then some default values must be taken.

Here is an example. aTable is table of names

id=1 aName = bmw
id=2 aName= mersedes
id=3 aName= audi

bTable has list of cars and I must get them all

1    nameType =1
2    nameType =2
3    nameType =3
4    nameType =5

So I must show all 4 cars. And with my code I will show only 3, because nameType of number 4 car is 5. And there is no such ID in aTable. The result will be

1 car is bmw

2 car is mersedes

3 car is audi

What I want to do is in such case aTable to give some NULL values or something so the result must be like

1 car is bmw

2 car is mersedes

3 car is audi

4 car is NULL


Solution

  • You should use LEFT JOIN instead of INNER JOIN

    SELECT da.aName AS aName 
    FROM dbo.bTable 
    LEFT JOIN aTable da ON dbo.bTable.nameType = da.ID