mirror of
https://codeup.aliyun.com/64f7d6b8ce01efaafef1e678/coal/coal.git
synced 2026-01-25 07:46:40 +08:00
97 lines
1.7 KiB
PL/PgSQL
97 lines
1.7 KiB
PL/PgSQL
|
|
drop function if exists selfAndChildrenIds;
|
|
drop function if exists selfAndParentIds;
|
|
|
|
create or replace function self_and_children_ids(tb text, id text, includeSelf bool = true) returns text[] AS
|
|
$$
|
|
|
|
declare
|
|
|
|
ans text[];
|
|
sql text;
|
|
text1 text;
|
|
begin
|
|
-- logic
|
|
|
|
if includeSelf then
|
|
text1 = 'id' ;
|
|
else
|
|
text1 = 'parent_id' ;
|
|
end if;
|
|
|
|
sql = 'with recursive tmp as (select id
|
|
from ' ||
|
|
tb ||
|
|
'
|
|
where ' ||
|
|
text1 ||
|
|
' = $1
|
|
union all
|
|
select ' ||
|
|
tb ||
|
|
'.id
|
|
from ' ||
|
|
tb ||
|
|
'
|
|
inner join tmp on ' ||
|
|
tb ||
|
|
'.parent_id = tmp.id)
|
|
|
|
select array_agg(id)
|
|
from tmp';
|
|
|
|
execute sql into ans using id;
|
|
|
|
|
|
return ans;
|
|
end
|
|
$$ language plpgsql
|
|
;
|
|
|
|
|
|
|
|
create or replace function self_and_parent_ids(tb text, id text, includeSelf bool = true) returns text[] AS
|
|
$$
|
|
|
|
declare
|
|
|
|
ans text[];
|
|
sql text;
|
|
begin
|
|
-- logic
|
|
|
|
|
|
|
|
sql = 'with recursive tmp as (select id,parent_id
|
|
from ' ||
|
|
tb ||
|
|
'
|
|
where ' ||
|
|
|
|
'id = $1
|
|
union all
|
|
select ' ||
|
|
tb ||
|
|
'.id, ' || tb || '.parent_id
|
|
from ' ||
|
|
tb ||
|
|
'
|
|
inner join tmp on ' ||
|
|
tb ||
|
|
'.id = tmp.parent_id)
|
|
|
|
select array_agg(id)
|
|
from tmp ';
|
|
|
|
if not includeSelf
|
|
then
|
|
sql = sql || ' where id != $1';
|
|
end if;
|
|
|
|
execute sql into ans using id;
|
|
|
|
|
|
return ans;
|
|
end
|
|
$$ language plpgsql
|
|
; |