-1

Lets say I have two tables Phone and Color

So on the Phone table in contains PhoneID,make,colorID

And on the color table it contains colorID, colorname

The two colorIDs are linked with a FK, but it is possible for a Phone to have a blank colorID

If I want to display a table that has PhoneID,make,colorname even if it hasn't got a colorID

So I have got a query like this

SELECT [PhoneID], [make], [colorID], FROM [Phone]

INNER JOIN [Color]
ON Phone.colorID = [color].[colorID];

But I want it to display all results even if it doesn't have a colorID and I want it to display the colorname instead of the colorID.

I am a bit confused on how to do this Thanks

Ron Smith
  • 3,241
  • 1
  • 13
  • 16
user673906
  • 757
  • 6
  • 15
  • 30

4 Answers4

4

Instead of using INNER JOIN you should be using a LEFT JOIN.

Left Join Definition: "The LEFT JOIN keyword returns all rows from the left table (table1), with the matching rows in the right table (table2). The result is NULL in the right side when there is no match."

D_R
  • 4,894
  • 4
  • 45
  • 62
1

use left join that will

SELECT [PhoneID], [make], [colorID], FROM [Phone]
Left JOIN [Color]
ON Phone.colorID = [color].[colorID];

As far as the color name is concerned, you will have to join with color table and print colorName instead of id.

Danyal Sandeelo
  • 12,196
  • 10
  • 47
  • 78
1

You want to use a LEFT JOIN.

SELECT [PhoneID], [make], [colorID], FROM [Phone]
    LEFT JOIN [Color]
        ON Phone.colorID = [color].[colorID];
Community
  • 1
  • 1
Ron Smith
  • 3,241
  • 1
  • 13
  • 16
1

As suggested above, go for a Left Join to fetch required results. Also, if you need to display color name instead of colorID, check the SQL function ISNULL (assuming you are using MS SQL Server). ISNULL function will allow you to set a default value when colorID is blank

So something like:

select phoneID, make, ISNULL(colorID, 'your_default_value') FROM .....
LEFT JOIN ......
Kedar Joshi
  • 1,182
  • 1
  • 20
  • 27