选择[COLUMN_NAME] AS,自引用表格

时间:2015-09-04 09:06:41

标签: postgresql tree hierarchy self-referencing-table

以下是我在自引用表 emp_tabref1

上执行的函数 get_reportees
CREATE OR REPLACE FUNCTION get_reportees4(IN id integer)
RETURNS TABLE(e_id integer, e_name character varying, e_manager integer, e_man_name character varying) AS
$$
BEGIN
RETURN QUERY
WITH RECURSIVE manger_hierarchy(e_id, e_name, m_id, m_name) AS 
(
SELECT e.emp_id, e.emp_name, e.mgr_id, e.emp_name AS man_name
FROM emp_tabref1 e WHERE e.emp_id = id
UNION
SELECT rp.emp_id, rp.emp_name, rp.mgr_id, rp.emp_name AS man_name
FROM manger_hierarchy mh INNER JOIN emp_tabref1 rp ON mh.e_id = rp.mgr_id
)
SELECT * from manger_hierarchy;
END;
$$ LANGUAGE plpgsql VOLATILE

emp_tabref1的表结构:

CREATE TABLE **emp_tabref1**
(
emp_id integer NOT NULL,
emp_name character varying(50) NOT NULL,
mgr_id integer,
CONSTRAINT emp_tabref_pkey PRIMARY KEY (emp_id),
CONSTRAINT emp_tabref_mgr_id_fkey FOREIGN KEY (mgr_id)
  REFERENCES emp_tabref (emp_id) MATCH SIMPLE
  ON UPDATE NO ACTION ON DELETE NO ACTION
)

我想要返回的是我们传递的id的层次结构(上面和下面),它将包含emp_name,emp_id,mgr_id和 mgr_name

但我的功能是这样回来的:

select * from get_reportees4(9)

   e_id e_name  e_manager e_man_name
1    9  "Emp9"  10        "Emp9"
2    5  "Emp5"  9         "Emp5"
3    6  "Emp6"  9         "Emp6"

我的预期输出是

       e_id e_name  e_manager e_man_name
1    9  "Emp9"        10        "Emp10"
2    5  "Emp5"         9        "Emp9"
3    6  "Emp6"         9        "Emp9"

该函数应返回管理员名称而不是员工姓名。请帮忙!

1 个答案:

答案 0 :(得分:0)

找到解决方案!通过使用mgr_id和emp_id

在临时manger_hierarchy表和emp_tabref1表之间创建新连接
CREATE OR REPLACE FUNCTION get_reportees4(IN id integer)
RETURNS TABLE(e_id integer, e_name character varying, e_manager integer, e_man_name character varying) AS
$$
BEGIN
RETURN QUERY 
WITH RECURSIVE manger_hierarchy(e_id, e_name, m_id, m_name) AS 
(
SELECT e.emp_id, e.emp_name, e.mgr_id, e.emp_name AS man_name
FROM emp_tabref1 e WHERE e.emp_id = id
UNION
SELECT rp.emp_id, rp.emp_name, rp.mgr_id, rp.emp_name AS man_name
FROM manger_hierarchy mh INNER JOIN emp_tabref1 rp ON mh.e_id = rp.mgr_id 
)
SELECT manger_hierarchy.e_id, manger_hierarchy.e_name, manger_hierarchy.m_id, emp_tabref1.emp_name 
FROM manger_hierarchy LEFT JOIN emp_tabref1 ON manger_hierarchy.m_id = emp_tabref1.emp_id;
END;
$$ LANGUAGE plpgsql VOLATILE

SELECT manger_hierarchy.e_id,manger_hierarchy.e_name,manger_hierarchy.m_id,emp_tabref1.emp_name     FROM manger_hierarchy LEFT JOIN emp_tabref1 ON manger_hierarchy.m_id = emp_tabref1.emp_id;