1

我想创建一个函数,它返回老板比人高多少级(调用函数)。

这是我想做的方式,但我不太清楚 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

如果有人能提供一些启示,那就太好了,

谢谢!

4

2 回答 2

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;
于 2012-12-05T08:17:16.910 回答
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
于 2012-12-05T07:41:09.527 回答