用于查询同一个表的SQL表列

时间:2013-10-16 18:55:53

标签: sql nested

我在数据库中的表格中遇到以下问题。

我有以下用户表(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列中有一个关联的条目,例如

User2最后被管理员用户更改为changed_by_value = 1

我想做的不是在SQL查询结果中使用数字changed_by_value,而是希望得到该用户的名称,即Admin。

我已尝试过各种方法,但到目前为止无济于事:

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 个答案:

答案 0 :(得分: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
相关问题