在Postgres中将列拆分为多行

编程入门 行业动态 更新时间:2024-10-26 10:29:06
本文介绍了在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中将列拆分为多行

本文发布于:2023-07-09 14:58:27,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1087143.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:中将   Postgres

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!