我正在创建一个从数据库中删除产品类别的函数。首先,它选择将从要删除的表继承的所有子表,如果子类别依赖于它,将返回表名的JSON对象。用SELECT查询中的值填充数组的最有效方法是什么?
CREATE OR REPLACE FUNCTION delete_category(catid INT)
RETURNS json AS $$
DECLARE
depend "catalog";
dependlist "catalog"[];
BEGIN
FOR depend IN SELECT * FROM catalog LOOP
dependlist:=dependlist || depend;
END LOOP;
END;
$$ LANGUAGE plpgsql;
答案 0 :(得分:0)
使用append ||
运算符非常慢-在某些较旧的PostgreSQL版本上,它非常慢。您可以使用两种可能性-提到的array_agg
或ARRAY(SUBSELECT)
构造函数:
dependlist := ARRAY(SELECT depend FROM catalog);
或
dependlist := (SELECT array_agg(depend) FROM catalog);
或
SELECT array_agg(depend) FROM catalog INTO dependlist;
所有情况下的性能都应相同。
答案 1 :(得分:0)
我使用了array_agg()函数,并且工作正常。我唯一不确定的是为什么我在FROM中的表名后面添加了depend?
CREATE OR REPLACE FUNCTION delete_category(catid INT)
RETURNS jsonb AS $$
DECLARE
--depend "catalog";
dependlist "catalog"[];
cnt INT;
BEGIN
--Check no other tables dependent
SELECT array_agg(depend) INTO dependlist FROM catalog depend
WHERE inherit_from=catid;
IF array_length(dependlist,1) IS NOT NULL THEN
RETURN jsonb_build_object('error',
'children','tables',to_jsonb(dependlist));
END IF;
--Check table is empty of products
SELECT COUNT(*) INTO cnt FROM (SELECT tablename
FROM catalog WHERE catalogid=catid) AS tname;
RETURN jsonb_build_object('error','none');
END;
$$ LANGUAGE plpgsql;