在postgres中展平嵌套记录

时间:2014-02-26 11:57:50

标签: sql postgresql

如何展平外部选择中的foo列(在PostgreSQL中)?

WITH RECURSIVE t AS (
    SELECT row(d.*) as foo FROM some_multicolumn_table as d
UNION ALL
    SELECT foo FROM t WHERE random() < .5
)
SELECT foo FROM t

我想要的是在外部选择中输出some_multicolumn_table的所有列(水平地,即作为多行的一行),而不仅仅是单个“记录”列。

怎么做?

1 个答案:

答案 0 :(得分:2)

您不需要ROW构造函数,因此您可以使用(foo).*扩展记录:

WITH RECURSIVE t AS (
    SELECT d as foo FROM some_multicolumn_table as d
UNION ALL
    SELECT foo FROM t WHERE random() < .5
)
SELECT (foo).* FROM t;

虽然这个查询可以简单地写成:

WITH RECURSIVE t AS (
    SELECT d.* FROM some_multicolumn_table as d
UNION ALL
    SELECT t.* FROM t WHERE random() < .5
)
SELECT * FROM t;

我建议尽量保持简单。但我认为这只是一个例证。