0

I have the following sql statement:

SELECT Useraccount.Name, Company.Name FROM Useraccount, Company WHERE Useraccount.CompanyId = Company.ID 

This statement shows all useraccount-names and the name of their company.

But I also have useraccounts where the companyId is 0 and I'd like to get them displayed too (Name of the company could be an empty string in this case). How can I do that?

1
  • And don't use 0. I don't like them but that's what NULLis for. You can add an explicit foreign key constraint if you convert the 0s to Nulls. Commented Mar 17, 2013 at 18:37

4 Answers 4

1

Use LEFT JOIN instead:

SELECT Useraccount.Name, Company.Name FROM Useraccount LEFT JOIN Company ON Useraccount.CompanyId = Company.ID; 

You were INNER JOINing the two tables with the old JOIN syntax. Please avoid this old join syntax and use the ANSI SQL-92 explicit syntax using the JOIN keyword. See this for more information:

For more info about the different join types:

Sign up to request clarification or add additional context in comments.

Comments

1

A LEFT JOIN would do the trick for you:

SELECT Useraccount.Name, Company.Name FROM Useraccount LEFT JOIN Company ON Useraccount.CompanyId = Company.ID 

Comments

0

You can use -

SELECT Useraccount.Name, Company.Name FROM Useraccount, Company WHERE Useraccount.CompanyId = Company.ID or Useraccount.CompanyId =0 

Comments

0

When you use LEFT JOIN, you will get all rows from left table irrespective of the matching status of rows.

SELECT Useraccount.Name AS UserAccountName, Company.Name AS CompanyName FROM Useraccount LEFT JOIN Company ON Useraccount.CompanyId = Company.ID; 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.