Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select all data include another table even if null

Tags:

sql

mysql

Setup: (1) Employee table (employeeID, firstName, lastName)

(1) Shoe table (shoeID, Employee_employeeID, shoeName, shoeColor, shoeBrand)

I want to select all rows in Employee table and even if there is no matching EmployeeID (Employee_EmployeeID) in the shoe table display that entire row anyway. Example desired output:

 EmployeeID  | firstName    | lastName    | shoeName     |   shoeColor  | shoeBrand

 1            John           Smith         AirMax2          Red          Nike
 2            Ronald         Mcdonald      null             null         null
 3            James          Knight        null             null         null
 4            Cindy          Smith         Pump             Brown        Cole Haan

I have tried a lot of different joins and I will get duplicate rows for each Employee.

like image 907
Jordan Avatar asked Feb 06 '13 22:02

Jordan


People also ask

How would you return data from 2 tables even if there are no matches?

The SQL LEFT JOIN returns all rows from the left table, even if there are no matches in the right table. This means that if the ON clause matches 0 (zero) records in the right table; the join will still return a row in the result, but with NULL in each column from the right table.

How do I join two tables with NULL values in SQL?

Since it's not possible to join on NULL values in SQL Server like you might expect, we need to be creative to achieve the results we want. One option is to make our AccountType column NOT NULL and set some other default value. Another option is to create a new column that will act as a surrogate key to join on instead.

How do you SELECT all records from one table that do not exist in another table SQL?

How to Select All Records from One Table That Do Not Exist in Another Table in SQL? We can get the records in one table that doesn't exist in another table by using NOT IN or NOT EXISTS with the subqueries including the other table in the subqueries.


2 Answers

try this

   SELECT e.employeeId,e.firstName,e.lastName,s.ShoeName,s.ShoeColor,s.ShoeBrand 
   FROM    Employee e
   LEFT JOIN Shoe s
   ON e.employeeID = s.Employee_employeeID

DEMO SQLFIDDLE HERE

like image 128
echo_Me Avatar answered Sep 28 '22 13:09

echo_Me


You are going to want to use a LEFT JOIN:

select e.employeeId,
  e.firstName,
  e.lastName,
  s.ShoeName,
  s.ShoeColor,
  s.ShoeBrand
from Employee e
left join shoe s
  on e.employeeID = s.Employee_employeeID

See SQL Fiddle with Demo

A LEFT JOIN will return the matching rows from the employee table even if there is not a matching row in the shoe table.

If you need help learning JOIN syntax, here is a great visual explanation of joins.

Now, if you wanted all rows that match both tables, then you would use an INNER JOIN.

like image 25
Taryn Avatar answered Sep 28 '22 14:09

Taryn