如何从Postgresql子查询的同一张表中获取用户名而不是ID?

时间:2018-10-10 17:58:43

标签: sql postgresql

我有一个用户表: 具有以下字段: 名,姓...,经理ID ...,

manager_id只是另一个用户的ID。

当我运行查询时:

   SELECT DISTINCT ON(users.id) user.id, CONCAT(users.first_name, ' ', users.last_name) AS \
                'employee', users.email, \
                (SELECT manager_id), \
                (SELECT users.first_name from users where users.id = manager_id) as Manager,\
                (SELECT DISTINCT to_char(auth_user.last_login, 'Mon dd, yyyy')) as Last_Login FROM users INNER JOIN auth_user ON (users.user_id = auth_user.id)

此查询(SELECT manager_id)返回经理的ID,但是返回下一行

  

(SELECT users.first_name from users where users.id = manager_id) as Manager

返回空白。 我还尝试将表本身连接起来,该表仅返回1位经理的姓名:

  

(SELECT e.first_name FROM employees_employee e INNER JOIN employees_employee s ON s.id = e.coach_id limit 1)

1 个答案:

答案 0 :(得分:2)

这是因为没有用户是他们自己的管理员。 始终限定您的列名!

SELECT DISTINCT ON (u.id) u.id,
       CONCAT(u.first_name, ' ', u.last_name) AS employee
       u.email,
       u.manager_id,
       (SELECT u2.first_name FROM users u2 where u2.id = u.manager_id) as Manager,
       to_char(au.last_login, 'Mon dd, yyyy') as Last_Login
FROM users u INNER JOIN
     auth_user au
     ON u.user_id = au.id
ORDER BY u.user_id;