从另一个表中选择数据SQL选择查询

时间:2014-04-04 09:34:26

标签: c# sql sql-server vb.net performance

这是由StaffID

连接的2个表
Job Table
=========
JobID AssignedTo(StaffID) Created By(StaffID)
1     2                   1
2     3                   2

Staff Table
============
StaffID Name
1       May
2       Bob
3       Mary

我需要一个SQL语句来获取具有相应人员姓名的作业详细信息,但是这样做有问题,因为我无法区分列,因为他们使用相同的表。最终结果应如下所示

JobID Assigned To  Created By
1     Bob          May
2     Mary         Bob   

1 个答案:

答案 0 :(得分:3)

您需要两次加入Staff

select J.JobId, S1.Name AS AssignedTo, S2.Name AS CreatedBy
from Job J
inner join Staff S1 on S1.StaffID = J.AssignedTo
inner join Staff S2 on S2.StaffID = J.CreatedBy