有没有办法根据 Postgres 中的计数器列重复行?
Is there a way to repeat rows based on a counter column in Postgres?
我有两个 tableA 和 B。
A 在 table B 中有一个行的 ID,以及一个计数器:
b_id integer not null references B(id),
count integer not null default 1
在 Postgres 中有没有办法 return 使用 B 中重复 count
次的行查询 A?
是的。使用 generate_series()
:
select t.*, n
from t cross join lateral
generate_series(1, t.count, 1) gs(n);
以上其实是逻辑的冗长写法。我更喜欢上面的内容,因为它非常明确地说明了正在发生的事情。但是,您可以将其简化为:
select t.*, generate_series(1, t.count, 1) as n
from t;
我有两个 tableA 和 B。
A 在 table B 中有一个行的 ID,以及一个计数器:
b_id integer not null references B(id),
count integer not null default 1
在 Postgres 中有没有办法 return 使用 B 中重复 count
次的行查询 A?
是的。使用 generate_series()
:
select t.*, n
from t cross join lateral
generate_series(1, t.count, 1) gs(n);
以上其实是逻辑的冗长写法。我更喜欢上面的内容,因为它非常明确地说明了正在发生的事情。但是,您可以将其简化为:
select t.*, generate_series(1, t.count, 1) as n
from t;