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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14740438/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 16:26:10  来源:igfitidea点击:

Select all data include another table even if null

mysqlsql

提问by Jordan

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

设置:(1)员工表(employeeID、firstName、lastName)

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

(1) 鞋表(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:

我想选择 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

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

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

回答by echo_Me

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

演示 SQLFIDDLE 在这里

回答by Gordon Linoff

You need a left outer join:

你需要一个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

回答by Taryn

You are going to want to use a LEFT JOIN:

你会想要使用一个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

参见SQL Fiddle with Demo

A LEFT JOINwill return the matching rows from the employeetable even if there is not a matching row in the shoetable.

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

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

如果您需要帮助学习JOIN语法,这里是joins 的一个很好的视觉解释

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

现在,如果您想要匹配两个表的所有行,那么您可以使用INNER JOIN.