對於逗號分隔的字串,使用string_to_table()
函數取代unnest(string_to_array())
:
<code class="language-sql">SELECT t.id, a.elem, a.nr FROM tbl 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>
使用row_number() OVER (PARTITION BY id)
(無ORDER BY
)取得序號:
<code class="language-sql">SELECT *, row_number() OVER (PARTITION by id) AS nr FROM (SELECT id, regexp_split_to_table(elements, ',') AS elem FROM tbl) t;</code>
實作自訂函數f_unnest_ord()
,用於帶序號地拆分元素:
<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';</code>
以上是如何在 PostgreSQL 中有效解除逗號分隔字串的嵌套?的詳細內容。更多資訊請關注PHP中文網其他相關文章!