2017-04-04 54 views
0

我想在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 
+2

做在表示层。 – jarlh

+0

http://stackoverflow.com/questions/4097266/basic-sql-selecting-the-same-column-multiple-times-in-one-query-when-each-occ –

+0

@Geek Junior你可以做它与子查询 –

回答

4

可以越过加入针对generate_series(1,4),这将返回一个包含数字1〜4的表中:

SELECT mytable.* 
FROM mytable 
CROSS JOIN generate_series(1,4) as x 
WHERE id=1 

对于原始结果集中的每一行,将会有一个副本,旁边有1个副本,其中一个具有2,依此类推。

+0

正是我在找什么,我红了很多关于generate_series,但无法弄清楚如何使用它跨越我的大查询。刚刚测试过!工作正常。 谢谢 –

2

可以使用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) 
+0

根据我原来的查询多个连接有点复杂,我试图在我的例子中简单 –

0

使用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 
+0

有用,但它会使我的查询变大! –

-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) 
+0

这是postgres没有oracle –

+0

该方法是有道理的,但只需要从''dual''和已经从问题中的伪代码复制的'4x'移除。 – IMSoP

相关问题