我有两张桌子:
Employees (columns: ID, Name)
和
employee partners (EmployeeID1, EmployeeID2, Time)
我想输出EmployeName1,EmployeeName2,Time而不是imployee id。
(换句话说,用名称替换id,但一次用两列替换)
我该怎么做? JOIN会成为合适的命令吗?
答案 0 :(得分:1)
您需要加入员工表2次,因为员工合作伙伴表会充当多个连接。 选择应该是:
SELECT emp1.name, emp2.name, em.time
FROM Employees emp1
JOIN employee_partners em ON emp1.id = EmployeeID1
JOIN Employees emp2 on emp2.id = EmployeeID2
答案 1 :(得分:1)
通常在这些情况下,您希望使用LEFT JOIN
:
SELECT e1.name as name1, e2.name as name2, em.time
FROM employee_partners ep LEFT JOIN
Employees e1
ON e1.id = ep.EmployeeID1 LEFT JOIN
Employees e2
ON e2.id = ep.EmployeeID2;
注意:
LEFT JOIN
,则NULL
确保您不会丢失行。