我想在PostgreSQL中打印4次同一行,如何實現?如何在PostgreSQL中多次選擇單個行
Table : mytable
Id | name
------------
1 | foo
2 | bar
3 | zzz
我想是這樣
Select 4x mytable.* from mytable where id=1
而且結果應該是
Id | name
------------
1 | foo
1 | foo
1 | foo
1 | foo
我想在PostgreSQL中打印4次同一行,如何實現?如何在PostgreSQL中多次選擇單個行
Table : mytable
Id | name
------------
1 | foo
2 | bar
3 | zzz
我想是這樣
Select 4x mytable.* from mytable where id=1
而且結果應該是
Id | name
------------
1 | foo
1 | foo
1 | foo
1 | foo
可以越過加入針對generate_series(1,4)
,這將返回一個包含數字1〜4的表中:
SELECT mytable.*
FROM mytable
CROSS JOIN generate_series(1,4) as x
WHERE id=1
對於原始結果集中的每一行,將會有一個副本,旁邊有1個副本,其中一個具有2,依此類推。
正是我在找什麼,我紅了很多關於generate_series,但無法弄清楚如何使用它跨越我的大查詢。剛剛測試過!工作正常。 謝謝 –
可以使用generate_series
。
樣品:
t=# create table so48 (i int,n text);
CREATE TABLE
t=# insert into so48 select 1,'a';
INSERT 0 1
t=# insert into so48 select 2,'b';
INSERT 0 1
選擇:
t=# with s as (select generate_series(1,4,1) g) select so48.* from so48 join s on true where i = 1;
i | n
---+---
1 | a
1 | a
1 | a
1 | a
(4 rows)
根據我原來的查詢多個連接有點複雜,我試圖在我的例子中簡單 –
使用union all
Select mytable.* from mytable where id=1
union all Select mytable.* from mytable where id=1
union all Select mytable.* from mytable where id=1
union all Select mytable.* from mytable where id=1
有用,但它會使我的查詢變大! –
CROSS JOIN應該做的工作
Select 4x mytable.* from mytable where id=1
cross join
(select 1 from dual union all
select 1 from dual union all
select 1 from dual union all
select 1 from dual)
這是postgres沒有oracle –
該方法是有道理的,但只需要從''dual''和已經從問題中的僞代碼複製的'4x'移除。 – IMSoP
做在表示層。 – jarlh
http://stackoverflow.com/questions/4097266/basic-sql-selecting-the-same-column-multiple-times-in-one-query-when-each-occ –
@Geek Junior你可以做它與子查詢 –