2012-11-18 124 views
3

MS SQL Server數據庫。SQL,獲取外鍵值。外鍵引用同一個表

我有這樣的簡單結構:(不是在正確的地方比較遺憾的主鍵)

enter image description here

教師表我有一個外鍵「行政化」,它引用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 

回答

10

JOINTEACHER表一次,像這樣:

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,但這是推薦的語法。

+0

完美,謝謝! – Aremyst

+0

SQL服務器是否真的允許使用單引號指定列別名,這些引號表示字符文字,而不是SQL中的標識符? –

+0

@a_horse_with_no_name - 據我所知,是的,它允許使用單引號指定列別名。但是我這樣寫它被格式化爲輸出的字符文字。但是,你有什麼建議呢? –

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