在Postgres中将列拆分为多行 [英] Split column into multiple rows in Postgres

查看:154
本文介绍了在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?

这篇关于在Postgres中将列拆分为多行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆