PL/PGSQL 查询仅返回第一行 (Supabase)
PL/PGSQL query is returning only the first row (Supabase)
我需要从 jobs
table 查询数据并插入 clients
table 到两个不同的列中。
首先我抓取客户名称放在 name
列,然后我抓取客户的 unpaid/partially 个付费工作列表作为对象数组放在 open_jobs
列。
下面的代码有效,但它只 returns 第一行。
do $$
declare
x varchar;
y json;
begin
select distinct customer
into x
from jobs
order by customer asc;
select array_to_json(array_agg(row_to_json(t)))
from (
select job_location, job_total, paid, invoice_no
into y
from jobs
where customer = x and paid < job_total
order by invoice_no asc
)t;
insert into clients(name, open_jobs)
values(x, y);
end;
$$ language plpgsql;
我放了一张link查询结果的图片供参考
Query Result
详细说明我的评论(未测试):
do $$
declare
x varchar;
y json;
begin
FOR x IN select distinct customer from jobs
order by customer asc LOOP
select array_to_json(array_agg(row_to_json(t)))
from (
select job_location, job_total, paid, invoice_no
into y
from jobs
where customer = x and paid < job_total
order by invoice_no asc
)t;
insert into clients(name, open_jobs)
values(x, y);
END LOOP;
end;
$$ language plpgsql;
您的原始函数只会select 客户查询返回的第一个值。通过使用 FOR x IN ... LOOP ... END LOOP
您可以遍历查询的所有结果。
我需要从 jobs
table 查询数据并插入 clients
table 到两个不同的列中。
首先我抓取客户名称放在 name
列,然后我抓取客户的 unpaid/partially 个付费工作列表作为对象数组放在 open_jobs
列。
下面的代码有效,但它只 returns 第一行。
do $$
declare
x varchar;
y json;
begin
select distinct customer
into x
from jobs
order by customer asc;
select array_to_json(array_agg(row_to_json(t)))
from (
select job_location, job_total, paid, invoice_no
into y
from jobs
where customer = x and paid < job_total
order by invoice_no asc
)t;
insert into clients(name, open_jobs)
values(x, y);
end;
$$ language plpgsql;
我放了一张link查询结果的图片供参考
Query Result
详细说明我的评论(未测试):
do $$
declare
x varchar;
y json;
begin
FOR x IN select distinct customer from jobs
order by customer asc LOOP
select array_to_json(array_agg(row_to_json(t)))
from (
select job_location, job_total, paid, invoice_no
into y
from jobs
where customer = x and paid < job_total
order by invoice_no asc
)t;
insert into clients(name, open_jobs)
values(x, y);
END LOOP;
end;
$$ language plpgsql;
您的原始函数只会select 客户查询返回的第一个值。通过使用 FOR x IN ... LOOP ... END LOOP
您可以遍历查询的所有结果。