在 PostgreSQL 中处理包含逗号分隔值的列时,可以使用 unnest()
函数提取单个元素。但是,如果您需要在输出中包含元素序号,则可以考虑几种方法。
利用 string_to_table()
函数:
<code class="language-sql">SELECT t.id, a.elem, a.nr FROM tbl AS t LEFT JOIN LATERAL string_to_table(t.elements, ',') WITH ORDINALITY AS a(elem, nr) ON true;</code>
对于返回集合的函数,使用 WITH ORDINALITY
:
<code class="language-sql">SELECT t.id, a.elem, a.nr FROM tbl AS t LEFT JOIN LATERAL unnest(string_to_array(t.elements, ',')) WITH ORDINALITY AS a(elem, nr) ON true;</code>
或者,基于实际数组:
<code class="language-sql">SELECT t.id, a.elem, a.nr FROM tbl AS t LEFT JOIN LATERAL unnest(t.arr) WITH ORDINALITY AS a(elem, nr) ON true;</code>
用 row_number() OVER (PARTITION BY id)
替换 ORDER BY
:
<code class="language-sql">SELECT id, elem, row_number() OVER (PARTITION by id) AS nr FROM (SELECT id, regexp_split_to_table(elements, ',') AS elem FROM tbl);</code>
使用函数模拟该功能:
<code class="language-sql">CREATE FUNCTION f_unnest_ord(anyarray, OUT val anyelement, OUT ordinality integer) RETURNS SETOF record LANGUAGE sql IMMUTABLE AS 'SELECT [i], i - array_lower(,1) + 1 FROM generate_series(array_lower(,1), array_upper(,1)) i'; SELECT id, arr, (rec).* FROM ( SELECT *, f_unnest_ord(arr) AS rec FROM ( VALUES (1, '{a,b,c}'::text[]) -- short for: '[1:3]={a,b,c}' , (2, '[5:7]={a,b,c}') , (3, '[-9:-7]={a,b,c}') ) t(id, arr) ) sub;</code>
以上是在 PostgreSQL 中取消嵌套逗号分隔值时如何获取元素编号?的详细内容。更多信息请关注PHP中文网其他相关文章!