如何在PostgreSql中多次选择单行

时间:2017-04-04 09:19:06

标签: sql postgresql

我想在PostgreSQL中打印同一行4次,如何实现呢?

<i id='new_contact' class="plus" title='Create contact' data-placement="left" data-toggle="tooltip" data-head="New sms">
			</i>

我想要像

这样的东西
Table : mytable

Id   |  name
------------
 1   |  foo
 2   |  bar
 3   |  zzz

结果应该是

Select 4x mytable.* from mytable where id=1

4 个答案:

答案 0 :(得分:4)

您可以与generate_series(1,4)交叉加入,这将返回包含数字1到4的表格:

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

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

答案 1 :(得分: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)

答案 2 :(得分: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

答案 3 :(得分:-1)

交叉联接应该完成这项工作

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 )