4

MS SQL 服务器数据库。

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

在此处输入图像描述

在 TEACHER 表中,我有一个外键“Chief”,它引用 TEACHER.ID(同一张表)。在进行 SELECT 查询时,如何获取不是整数(Teacher.ID),而是一个酋长的姓名(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
4

2 回答 2

12

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-92JOIN语法而不是您在查询中使用的旧语法。它们是相同的,但这是推荐的语法。

于 2012-11-18T08:57:18.613 回答
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
于 2012-11-18T08:59:15.610 回答