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
Select all data include another table even if null
提问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
回答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
A LEFT JOIN
will return the matching rows from the employee
table even if there is not a matching row in the shoe
table.
即使表中没有匹配的行,ALEFT JOIN
也会从employee
表中返回匹配的行shoe
。
If you need help learning JOIN
syntax, 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
.