SQL Query使用不同的值拉取相同的字段

时间:2015-04-17 15:52:25

标签: mysql sql

我有两个表,员工记录(id,firstName,lastName)和违规(violatorId,supervisorId)。

我的查询会列出违规者和监督者名单。我想而不是显示该人的身份,显示他们的名字和姓氏。所以这是我到目前为止的询问......

SELECT 
emp.firstName as vFirstName,
emp.lastName as vLastname,
v.violatorId, 
v.supervisorId,
emp.firstName as sFirstName,
emp.lastName as sLastName
FROM employee emp
LEFT JOIN violator v
ON violatorId = emp.id

因此,这将返回违规者的姓名和姓氏信息,但不会返回主管。样本输出:

Violator vFirstName  vLastName   Supervisor sFirstName sLastName
1        Jon         Smith       20         Jon        Smith

任何帮助都会很棒

3 个答案:

答案 0 :(得分:3)

SELECT 
  e1.firstName AS violatorFirstName,
  e1.lastName AS violatorLastName,
  e2.firstName AS supervisorFirstName,
  e2.lastName AS supervisorLastName
FROM violator v
LEFT JOIN employee e1 ON v.violatorId = e1.id
LEFT JOIN employee e2 ON v. supervisorId = e2.id

答案 1 :(得分:2)

您需要再次加入employee

SELECT emp.firstName AS vFirstName, emp.lastName AS vLastName,
       v.violatorId AS vId, v.supervisorId AS sId,
       s.firstName AS sFirstName, s.lastName AS sLastName
FROM employee emp
LEFT JOIN violator v ON v.violatorId = emp.id
LEFT JOIN employee s ON v.supervisorId = s.id

答案 2 :(得分:0)

<强>方法-1

SELECT 
  e1.violatorId AS violatorId ,
  e1.firstName AS violatorName,
  e2.supervisorId AS supervisorId ,
  e2.firstName AS supervisorName
FROM violator v
LEFT JOIN employee e1 ON v.violatorId = e1.id
LEFT JOIN employee e2 ON v. supervisorId = e2.id

<强>方法-2

SELECT 
    v.violatorId,
    emp.firstName AS violatorName, 
    v.supervisorId,
    (SELECT firstName FROM employee WHERE employee.id = v.supervisorId) AS supervisorName
FROM 
    employee emp
LEFT JOIN 
    violator v
ON 
    violatorId = emp.id