Select 和更新存储函数 Postgresql
Select and Update in Stored Functions Postgresql
我创建了一个用于获取数据的存储函数:
CREATE OR REPLACE FUNCTION sold_quantity()
RETURNS TABLE(
invoiceid BIGINT,
itemid BIGINT,
sum_sold_quantity NUMERIC)
AS $$
BEGIN
RETURN QUERY SELECT
invoice_id as invoiceid, item_id as itemid, sum(sold_quantity) as
sum_sold_quantity
FROM
invoice_item
WHERE
status='sold'
GROUP BY
invoice_id, item_id;
END; $$
LANGUAGE 'plpgsql';
如何存储此数据并使用它来更新下面的 table?
UPDATE invoice_item
SET sold_quantity = sum_sold_quantity
where invoice_id=invoiceid
and item_id = itemid;
我们如何将这两个查询(Select 和更新)合并到一个存储函数中,并执行以获取所有 500k 条包含上述三列的记录并批量更新(例如 10000 条记录)
可以直接在UPDATE语句中使用函数
UPDATE invoice_item ii
SET sold_quantity = sq.sum_sold_quantity
from sold_quantity() as sq
where ii.invoice_id = sq.invoiceid
and ii.item_id = sq.itemid;
对于仅 500.000 行,我根本不会费心进行任何批处理。只需在一条语句中更新所有行。
事实上你并不需要一个函数作为开头:
UPDATE invoice_item ii
SET sold_quantity = sq.sum_sold_quantity
from (
select invoice_id as invoiceid, item_id as itemid, sum(sold_quantity) as sum_sold_quantity
FROM invoice_item
WHERE status='sold'
GROUP BY invoice_id, item_id;
) as sq
where ii.invoice_id = sq.invoiceid
and ii.item_id = sq.itemid;
我创建了一个用于获取数据的存储函数:
CREATE OR REPLACE FUNCTION sold_quantity()
RETURNS TABLE(
invoiceid BIGINT,
itemid BIGINT,
sum_sold_quantity NUMERIC)
AS $$
BEGIN
RETURN QUERY SELECT
invoice_id as invoiceid, item_id as itemid, sum(sold_quantity) as
sum_sold_quantity
FROM
invoice_item
WHERE
status='sold'
GROUP BY
invoice_id, item_id;
END; $$
LANGUAGE 'plpgsql';
如何存储此数据并使用它来更新下面的 table?
UPDATE invoice_item
SET sold_quantity = sum_sold_quantity
where invoice_id=invoiceid
and item_id = itemid;
我们如何将这两个查询(Select 和更新)合并到一个存储函数中,并执行以获取所有 500k 条包含上述三列的记录并批量更新(例如 10000 条记录)
可以直接在UPDATE语句中使用函数
UPDATE invoice_item ii
SET sold_quantity = sq.sum_sold_quantity
from sold_quantity() as sq
where ii.invoice_id = sq.invoiceid
and ii.item_id = sq.itemid;
对于仅 500.000 行,我根本不会费心进行任何批处理。只需在一条语句中更新所有行。
事实上你并不需要一个函数作为开头:
UPDATE invoice_item ii
SET sold_quantity = sq.sum_sold_quantity
from (
select invoice_id as invoiceid, item_id as itemid, sum(sold_quantity) as sum_sold_quantity
FROM invoice_item
WHERE status='sold'
GROUP BY invoice_id, item_id;
) as sq
where ii.invoice_id = sq.invoiceid
and ii.item_id = sq.itemid;