为了论证,我有一个简单的表格。我有一个选择 id 并循环遍历它们的函数,称为loop_test
. 我可以选择一组 id 并循环遍历它们,从而导致我在事务中发生更改。
CREATE OR REPLACE FUNCTION loop_test() RETURNS void AS $$
DECLARE
_ids_array INTEGER[];
_id INTEGER;
BEGIN
SELECT ARRAY(SELECT id FROM loop_test) INTO _ids_array;
FOREACH _id IN ARRAY _ids_array
LOOP
UPDATE loop_test SET looped = TRUE WHERE id = _id;
END LOOP;
END;
$$ LANGUAGE plpgsql;
桌子:
db=# \d loop_test;
Table "public.loop_test"
Column | Type | Modifiers
---------------+---------+-----------
id | integer |
other_id | integer |
id_copy | integer |
other_id_copy | integer |
looped | boolean |
db=# select * from loop_test;
id | other_id | id_copy | other_id_copy | looped
----+----------+---------+---------------+--------
1 | 10 | | |
6 | 15 | | |
2 | 11 | | |
7 | 16 | | |
3 | 12 | | |
4 | 13 | | |
5 | 14 | | |
(7 rows)
当我打电话时select loop_test()
,我得到以下结果:
db=# select * from loop_test;
id | other_id | id_copy | other_id_copy | looped
----+----------+---------+---------------+--------
1 | 10 | | | t
6 | 15 | | | t
2 | 11 | | | t
7 | 16 | | | t
3 | 12 | | | t
4 | 13 | | | t
5 | 14 | | | t
(7 rows)
但是,我想创建一个函数来选择 theid
和 theother_id
到一个数组中。有人告诉我使用类似的东西agg_array
,但我不完全理解它是如何工作的。
我在想像下面这样的事情?
CREATE OR REPLACE FUNCTION agg_loop_test() RETURNS void AS $$
DECLARE
_ids_array INTEGER[][];
_id INTEGER;
BEGIN
SELECT AGG_ARRAY(SELECT id, other_id FROM loop_test) INTO _ids_array;
FOREACH _id IN ARRAY _ids_array
LOOP
UPDATE loop_test SET id_copy = _id[0], other_id_copy = _id[1] WHERE id = _id[0];
END LOOP;
END;
$$ LANGUAGE plpgsql;