我想创建一个函数,它返回boss在人之上的多少级别(调用该函数)。
这是我想要的方式,但我不太清楚SQL语法是如何工作的 http://pastebin.com/dyDaGwf9
表格如下:
workerid name chefid
1 Bob
2 Alice 1
3 Joe 1
4 John 2
5 Dirk 4
6 Ralf 2
7 Lisa 1
8 Lyn 3
调用函数时的最终结果应该如下所示
函数调用:
Select workerid, name, rankFunction(workerid) from workers;
workerid name rank
1 Bob 0
2 Alice 1
3 Joe 1
4 John 2
5 Dirk 3
6 Ralf 2
7 Lisa 1
8 Lyn 2
如果有人可以说清楚会很好,
谢谢!
答案 0 :(得分:3)
你不需要一个函数,只需一个递归查询(从版本8.4开始提供):
WITH RECURSIVE chef as (
SELECT workerid, name, chefid, 0 AS rank FROM workers WHERE chefid is null
UNION ALL
SELECT workers.workerid, workers.name, workers.chefid, rank + 1
FROM workers JOIN chef ON workers .chefid = chef.workerid
)
SELECT workerid, name, rank FROM chef ORDER BY workerid;
答案 1 :(得分:1)
这是一个简单的递归:
CREATE OR REPLACE FUNCTION rankFunction(worker_id int)
RETURNS int AS
$BODY$
DECLARE
temp_chefid int;
BEGIN
temp_chefid := (SELECT chefid from workers where workerid = worker_id);
IF(temp_chefid IS NULL) THEN
RETURN 0;
ELSE RETURN 1 + rankFunction(temp_chefid);
END IF;
END;
$BODY$
LANGUAGE plpgsql VOLATILE