我有2张桌子,员工和部门。
部门(身份,部门)员工(id,department_id,姓名,以及更多人)
所以employees.department_id是departments.id的外键。
我需要显示表员工,但是我需要显示实际的部门名称而不是department_id(显示部门的ID),因此我需要放置departments.department来代替department_id。
我该怎么做?
答案 0 :(得分:16)
你的朋友说实话:p
您只需在两个表之间使用内部联接,如下所示:
SELECT d.name, e.name, e.email, ... FROM deparments d INNER JOIN employees e ON d.id = e.department_id.
您必须调整您的字段以获得所需的输出:)
答案 1 :(得分:7)
SELECT employees.id, employees.department_id, employees.name, departments.department
FROM employees
INNER JOIN departments ON employees.department_id = departments.id
答案 2 :(得分:1)
您不应该使用SELECT *
,只需要获取您真正想要的字段,只需截取表值即可。
赞SELECT department.name
答案 3 :(得分:0)
这应该适合你:
SELECT
E.Id
, D.Department
, E.Name
-- More stuff
FROM Employees E
INNER JOIN Departments D
ON D.id = E.department_id
答案 4 :(得分:0)
SELECT employees.*, department.department
FROM employees
INNER JOIN department ON employees.department_id = department.id