SQL,获取外键值。外键引用同一个表

时间:2012-11-18 08:54:03

标签: sql sql-server select key

MS SQL Server数据库。

我有这个简单的结构:(抱歉主键不在正确的位置)

enter image description here

在TEACHER表中我有一个外键“Chief”,它引用了TEACHER.ID(同一个表)。在进行SELECT查询时,我怎么能得到一个整数(Teacher.ID),而不是一个Chief的名字(TEACHER.Name for Chief)?

这个只得到一个整数(酋长的ID):

SELECT DEPARTMENT.Name, TEACHER.Name, TEACHER.IDCode, POST.Name, TEACHER.Tel, TEACHER.Salary, TEACHER.Rise, TEACHER.HireDate, Chief
FROM TEACHER, DEPARTMENT, POST
WHERE TEACHER.ID_Post = POST.ID AND
    TEACHER.ID_Department = DEPARTMENT.ID;
GO

2 个答案:

答案 0 :(得分:10)

再次{p> JOIN TEACHER表,如下所示:

SELECT 
  d.Name, 
  t.Name, 
  t.IDCode, 
  p.Name, 
  t.Tel, 
  t.Salary, 
  t.Rise, 
  t.HireDate, 
  chief.Name 'Chief Name'
FROM TEACHER t 
INNER JOIN TEACHER chief ON t.Chief = chief.ID
INNER JOIN DEPARTMENT d ON t.ID_Department = d.ID
INNER JOIN POST p ON t.ID_Post = p.ID;

并使用ANS-SQL-92 JOIN语法而不是您在查询中使用的旧语法。 They are the same,但这是推荐的语法。

答案 1 :(得分:1)

这应该有效:

SELECT DEPARTMENT.Name, TEACHER.Name, TEACHER.IDCode
    , POST.Name, TEACHER.Tel, TEACHER.Salary, TEACHER.Rise, TEACHER.HireDate, c.Name as ChiefName
    FROM TEACHER
    join DEPARTMENT on TEACHER.ID_Department = DEPARTMENT.ID
    Join POST on TEACHER.ID_Post = POST.ID
    Left Join TEACHER c on c.ID=TEACHER.Chief