在 UPDATE 部分使用并行 unnest 加注 "column does not exist"

Upsert with parallel unnest raises "column does not exist" in UPDATE part

我有一个需要更新插入的并行 unnest:

CREATE FUNCTION public.sort_category(category_ids integer[], sort integer[])
RETURNS void
AS $$
  INSERT INTO upsert (user_id, category_id, sort)
    SELECT sessions.user_id, category_id, sort_index
    FROM  UNNEST(, ) as input(category_id, sort_index), sessions
    WHERE sessions.session_token = 'a'
    ON CONFLICT (user_id, category_id) 
    DO 
      UPDATE SET sort = sort_index;
$$ LANGUAGE sql VOLATILE STRICT;

在我的命令行中,我收到此错误:

ERROR: column "sort_index" does not exist LINE 11: UPDATE SET sort = sort_index;

HINT: There is a column named "sort_index" in table "SELECT", but it cannot be referenced from this part of the query.

Fiddle 来了,有请。 fiddle 上的错误不同,但功能相同:

https://www.db-fiddle.com/f/xnUGCeonxPNEnaSikazka/0

您必须在 UPSERT 的 UPDATE 部分使用特殊的 table EXCLUDED

CREATE FUNCTION public.sort_category(category_ids integer[], sort integer[])
  RETURNS void
  LANGUAGE sql VOLATILE STRICT AS
$func$
INSERT INTO upsert (user_id, category_id, sort)
SELECT s.user_id, input.category_id, input.sort_index
FROM   unnest(, ) AS input(category_id, sort_index)
CROSS  JOIN sessions s
WHERE  s.session_token = 'a'
ON CONFLICT (user_id, category_id) DO UPDATE
SET    sort = EXCLUDED.sort;                      --  here!
$func$

db<>fiddle here

参见: