gpt4 book ai didi

sql - UPSERT 一行取决于两列值的唯一组合

转载 作者:行者123 更新时间:2023-11-29 12:24:07 26 4
gpt4 key购买 nike

<分区>

我在数据库中有下表:

CREATE TYPE status AS ENUM (
'void',
'steady',
'transition'
);

CREATE TABLE relations (
marker integer NOT NULL,
related integer[] NOT NULL,
status status DEFAULT 'void'::status NOT NULL,
id serial -- pgAdmin requires primary key
);

ALTER TABLE ONLY relations
ADD CONSTRAINT pkey_id PRIMARY KEY (id);

INSERT INTO relations (marker, related, status)
VALUES
(3, '{6}', 'steady'::status),
(3, '{2}', 'transition'::status),
(6, '{4}', 'void'::status),
(6, '{2}', 'steady'::status),
(4, '{2}', 'steady'::status),
(4, '{6}', 'void'::status);

表格是这样的:

 marker | related |   status   | id 
--------+---------+------------+----
3 | {6} | steady | 1
3 | {2} | transition | 2
6 | {4} | void | 3
6 | {2} | steady | 4
4 | {2} | steady | 5
4 | {6} | void | 6

marker/status 组合应该是唯一的,即使还没有对应的约束。这不是这里的问题。我也有这个功能:

CREATE OR REPLACE FUNCTION update_relations(integer, integer, status) RETURNS void
LANGUAGE plpgsql
AS $_$
BEGIN
update relations
set related = array_append(related,
(CASE
WHEN marker = $1 THEN $2
WHEN marker = $2 THEN $1
END)
)
where
marker in ($1,$2) AND
status = $3;
END;
$_$;

当我运行时

SELECT update_relations(3, 4, 'void'::status);

然后我想要 marker 值为 4status 为 'void' 的行更新其 related 值并将 3 附加到数组。因此,具有 marker = 3status = 'void'::status 的行应将 4 附加到其 related 数组。然而,这是结果:

 marker | related |   status   | id 
--------+---------+------------+----
3 | {6} | steady | 1
3 | {2} | transition | 2
6 | {4} | void | 3
6 | {2} | steady | 4
4 | {2} | steady | 5
4 | {6,3} | void | 6

如您所见,marker = 4status = 'void'::status 的行已按预期更新。由于没有对应的行满足 'marker = 3 and status = 'void'::status` 的要求,因此不会发生更新。在这种情况下,我想插入一行,这样结果就是:

 marker | related |   status   | id 
--------+---------+------------+----
3 | {6} | steady | 1
3 | {2} | transition | 2
6 | {4} | void | 3
6 | {2} | steady | 4
4 | {2} | steady | 5
4 | {6,3} | void | 6
3 | {4} | void | 7

如果所需的 marker/status 组合不存在,我该如何更新表格?

PS:我使用的是 postgres 9.4。

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com