我使用generate_series在表中插入值。并且generate_series在其范围内插入指定的值。
例如:对于下面的查询,
SELECT i AS id, i AS age, i AS house_number
INTO egg
FROM generate_Series(1,6) AS i;
我们得到的结果是:
id age house_number
1 1 1
2 2 2
3 3 3
4 4 4
5 5 5
6 6 6
但我的问题是,我想只插入到第3列"年龄",然后从0开始后3:
id age house_number
1 1 1
2 2 2
3 3 3
4 1 4
5 2 5
6 3 6
这可能吗?generate_series()
中是否有一些随机函数执行相同的功能?
您可以使用模运算从0循环到n - 1并加1:
SELECT i AS id, (i - 1) % 3 +1 AS age, i AS house_number
INTO egg
FROM generate_Series(1,6) AS i;
您可以使用设计的序列来做到这一点:
create table test (id serial);
alter sequence test_id_seq cycle minvalue 0 maxvalue 3 start 0 restart;
insert into test values(DEFAULT);
insert into test values(DEFAULT);
insert into test values(DEFAULT);
insert into test values(DEFAULT);
insert into test values(DEFAULT);
insert into test values(DEFAULT);
insert into test values(DEFAULT);
insert into test values(DEFAULT);
select * from test;
id
----
0
1
2
3
0
1
2
3
(8 rows)