选择所有数据包括另一个表,即使为null

时间:2013-02-06 22:53:28

标签: mysql sql

设定: (1)员工表(employeeID,firstName,lastName)

(1)鞋桌(shoeID,Employee_employeeID,shoeName,shoeColor,shoeBrand)

我想选择Employee表中的所有行,即使鞋表中没有匹配的EmployeeID(Employee_EmployeeID)显示整行也是如此。示例所需输出:

 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

我尝试了很多不同的连接,我会为每个Employee获得重复的行。

3 个答案:

答案 0 :(得分:20)

试试这个

   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

答案 1 :(得分:8)

您需要left outer join

select e.employeeid, e.firstname, e.lastname, s.shorname, s.shoecolor, s.shoebrand
from employee e left outer join
     shoe s
     on e.employeeid = s.employeeid

答案 2 :(得分:5)

您将要使用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

请参阅SQL Fiddle with Demo

即使LEFT JOIN表中没有匹配的行,employee也会返回shoe表中的匹配行。

如果您需要帮助学习JOIN语法,这里有一个很棒的visual explanation of joins

现在,如果您希望所有与两个表匹配的行,那么您将使用INNER JOIN