在 Postgres 中将列拆分为多行

编程入门 行业动态 更新时间:2024-10-26 04:33:17
本文介绍了在 Postgres 中将列拆分为多行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

假设我有一张这样的表:

Suppose I have a table like this:

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

subject 是 text 类型,flag 是 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

有没有简单的方法可以做到这一点?

Is there an easy way to do this?

推荐答案

在 Postgres 9.3+ 中使用 LATERAL join:

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() 不返回任何行(空或 NULL subject),结果将根本没有行.使用 LEFT JOIN unnest(...) i ON true 总是从 tbl 返回行.见:

It's an implicit LATERAL join. If unnest() does not return any rows (empty or NULL subject), the result will be no row at all. Use LEFT JOIN unnest(...) i ON true to always return rows from tbl. See:

  • 什么是LATERAL JOIN 和 PostgreSQL 子查询的区别?

您也可以使用 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()

更多推荐

在 Postgres 中将列拆分为多行

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

发布评论

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

>www.elefans.com

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