0

以下是我对自引用表 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"

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

4

1 回答 1

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

选择 manger_hierarchy.e_id,manger_hierarchy.e_name,manger_hierarchy.m_id,emp_tabref1.emp_name 从 manger_hierarchy LEFT JOIN emp_tabref1 ON manger_hierarchy.m_id = emp_tabref1.emp_id;

于 2015-09-04T09:55:23.333 回答