在 pl/pgsql-while 循环中更新单行 table
Update single-row table in pl/pgsql-while loop
create table data(a1 float, a2 float);
insert into data values(1::float, 1::float);
do $$
declare
counter integer := 0;
begin
while counter < 50 loop
--SAVE THIS INTO DATA
SELECT a1-0.1*random(),
a2-0.1*random()
from data group by a1, a;
--SAVE THIS INTO DATA (END)
counter := counter + 1;
end loop;
end$$;
我想将 a1
和 a2
的值保存到第一个数据元组中。 (基本上是 运行 个计数)
如何将 SELECT
的结果保存到现有的 table 中?
table 上的 PRIMARY KEY
会更容易:
create table data(id int primary key, a1 float, a2 float);
insert into data values(1, 1, 1);
select * from data;
id | a1 | a2
----+----+----
1 | 1 | 1
update data set a1 = a1 - 0.1*random(), a2 = a2 - 0.1*random() where id =1;
select * from data;
id | a1 | a2
----+--------------------+------------------
1 | 0.9039355377682678 | 0.98859843416964
然后将UPDATE
合并到计数器循环中:
do $$
declare
counter integer := 0;
begin
while counter < 50 loop
--SAVE THIS INTO DATA
update data set a1 = a1 - 0.1*random(), a2 = a2 - 0.1*random() where id =1;
--SAVE THIS INTO DATA (END)
counter := counter + 1;
end loop;
end$$;
select * from data;
id | a1 | a2
----+---------------------+--------------------
1 | -1.3146675853588001 | -1.216530003992667
create table data(a1 float, a2 float);
insert into data values(1::float, 1::float);
do $$
declare
counter integer := 0;
begin
while counter < 50 loop
--SAVE THIS INTO DATA
SELECT a1-0.1*random(),
a2-0.1*random()
from data group by a1, a;
--SAVE THIS INTO DATA (END)
counter := counter + 1;
end loop;
end$$;
我想将 a1
和 a2
的值保存到第一个数据元组中。 (基本上是 运行 个计数)
如何将 SELECT
的结果保存到现有的 table 中?
table 上的 PRIMARY KEY
会更容易:
create table data(id int primary key, a1 float, a2 float);
insert into data values(1, 1, 1);
select * from data;
id | a1 | a2
----+----+----
1 | 1 | 1
update data set a1 = a1 - 0.1*random(), a2 = a2 - 0.1*random() where id =1;
select * from data;
id | a1 | a2
----+--------------------+------------------
1 | 0.9039355377682678 | 0.98859843416964
然后将UPDATE
合并到计数器循环中:
do $$
declare
counter integer := 0;
begin
while counter < 50 loop
--SAVE THIS INTO DATA
update data set a1 = a1 - 0.1*random(), a2 = a2 - 0.1*random() where id =1;
--SAVE THIS INTO DATA (END)
counter := counter + 1;
end loop;
end$$;
select * from data;
id | a1 | a2
----+---------------------+--------------------
1 | -1.3146675853588001 | -1.216530003992667