WITH RECURSIVE r AS ( SELECT * FROM test_area WHEREid = 4 union ALL SELECT test_area.* FROM test_area, r WHERE test_area.fatherid = r.id ) SELECT * FROM r ORDERBYid; id |name | fatherid ----+--------+---------- 4 | 沈阳 | 2 7 | 和平区 | 4 8 | 沈河区 | 4 (3 rows)
WITH RECURSIVE r AS ( SELECT * FROM test_area WHEREid = 4 union ALL SELECT test_area.* FROM test_area, r WHERE test_area.id = r.fatherid ) SELECT * FROM r ORDERBYid; id | name | fatherid ----+------+---------- 1 | 中国 | 0 2 | 辽宁 | 1 4 | 沈阳 | 2 (3 rows)
备注:这正是我们想要的结果,接下来需要将 name 字段结果集合并成一行,我这里想到的是创建个function,当然也有其它方法。
CREATEorreplaceFUNCTION func_get_area(in in_id int4, out o_area text) AS $$ DECLARE v_rec_record RECORD; BEGIN o_area = ''; FOR v_rec_record IN (WITH RECURSIVE r AS (SELECT * FROM test_area WHEREid =in_id union ALL SELECT test_area.* FROM test_area, r WHERE test_area.id = r.fatherid)SELECTname FROM r ORDERBYid) LOOP o_area := o_area || v_rec_record.name; ENDLOOP; return; END; $$ LANGUAGE 'plpgsql';