Postgresql select,显示固定计数行

Postgresql select, show fixed count rows

简单的问题。我有一个有 3 行的 table "tablename"。当计数行 < 5 时,我需要在我的 select 中显示 5 行。

select * from tablename


+------------------+
|colname1 |colname2|
+---------+--------+
|1        |AAA     |
|2        |BBB     |
|3        |CCC     |
+---------+--------+

在这个查询中,我显示了 table 中的所有行。 但我需要显示 5 行。 2 行是空的。 例如(我需要):

+------------------+
|colname1 |colname2|
+---------+--------+
|1        |AAA     |
|2        |BBB     |
|3        |CCC     |
|         |        |
|         |        |
+---------+--------+    

最后两行是空的。 有可能吗?

像这样:

with num_rows (rn) as (
   select i
   from generate_series(1,5) i -- adjust here the desired number of rows
), numbered_table as (
   select colname1, 
          colname2,
          row_number() over (order by colname1) as rn
   from tablename
)
select t.colname1, t.colname2
from num_rows r
  left outer join numbered_table t on r.rn = t.rn;

这会为 tablename 中的每一行分配一个编号,并将其连接到固定数量的行。如果您知道 colname1 中的值始终是连续的且没有间隙(这种情况极不可能),那么您可以使用 row_number() 删除第二个 CTE 中行号的生成。

如果您不关心 哪个 行被 return 编辑,您可以省略 order by 部分 - 但匹配的行将是 随机 。省略 order by 会更有效率。


以上总是 return 恰好 5 行,无论 tablename 包含多少行。如果你想要至少 5行,那么你需要翻转外连接:

....
select t.colname1, t.colname2
from numbered_table t
  left outer join num_rows r on r.rn = t.rn;

SQLFiddle 示例:http://sqlfiddle.com/#!15/e5770/3