在Postgres中将列拆分为多行

问题描述:

假设我有一个这样的表:

Suppose I have a table like this:

    subject     | flag
----------------+------
 this is a test |    2

主题类型为文本标志的类型为 int 。我想在Postgres中将此表转换为类似的内容:

subject is of type text, and flag is of type int. I would like to transform this table to something like this in Postgres:

    token       | flag
----------------+------
 this           |    2
 is             |    2
 a              |    2
 test           |    2

有一种简单的方法吗?

在Postgres 9.3+中,使用 LATERAL 连接:

In Postgres 9.3+ use a LATERAL join:

SELECT s.token, flag
FROM   tbl t, unnest(string_to_array(t.subject, ' ')) s(token)
WHERE  flag = 2;

请注意, LATERAL 的简写形式如果 unnest()实际上返回行,则join仅返回行。

Note that the shorthand form of a LATERAL join only returns rows, if unnest() actually returns row(s).

您也可以使用 regexp_split_to_table() ,但这通常比较慢,因为正则表达式匹配的成本要高一些。

相关内容:

You could also use regexp_split_to_table(), but that's typically slower because regular expression matching costs a bit more.
Related:

  • SQL select rows containing substring in text field
  • PostgreSQL unnest() with element number
  • What is the difference between LATERAL and a subquery in PostgreSQL?