2013-10-16 20 views
0

我在我的數據庫中有一個關於表的問題。用於查詢同一個表的SQL表列

我已經具有以下列以下的用戶表(usertable1):

table_id row_id name changed_by_value department  lastlogon lastlogoff 
1000  1  Admin 1    main_department 10-16-2013 10-16-2013 
1000  2  User2 1    main_department 10-16-2013 10-16-2013 
1000  3  User3 1    main_department 10-16-2013 10-16-2013 
1000  4  User4 1    main_department 10-16-2013 10-16-2013 
1000  5  User5 1    main_department 10-16-2013 10-16-2013 

changed_by_value列爲數值並且是具有在row_id列中的相關條目例如

用戶2最後被Admin用戶更改爲changed_by_value = 1

我想要做的是,而不是在SQL查詢結果中具有數字changed_by_value,我想要該用戶的名稱,即管理員。

我已經試過這樣做,但無濟於事迄今爲止的各種方法:

select a.table_id, a.row_id, a.name, a.department, a.lastlogon, a.lastlogoff, 
(select b.name from usertable1 as b where a.changed_by_value = b.row_id) 
from usertable1 as a 

回答

1

我相信你只是尋找一個自連接,所以試試這個:

SELECT 
    a.table_id, a.row_id, a.name, a.department, 
    a.lastlogon, a.lastlogoff, 
    b.name AS 'Changed by' 
FROM usertable1 AS a 
INNER JOIN usertable1 AS b ON a.changed_by_value = b.row_id 
+0

謝謝jpw做了訣竅:) – user2887709

+0

@ user2887709如果我的回答很有用,請考慮接受它,以便將問題標記爲已回答。 :) – jpw