本文介绍了在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选择文本字段中包含子字符串的行
- 带有元素编号的PostgreSQL unnest()
- 什么是区别
- 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中将列拆分为多行
发布评论