postgresql 一行表postgres

azpvetkf  于 2023-06-29  发布在  PostgreSQL
关注(0)|答案(1)|浏览(190)

我试图创建一个只能容纳一行的表。下表工作正常,您不能在此表中插入多行。但是当我尝试使用ON CONFLICT更新该行时,它失败了。

CREATE TABLE IF NOT EXISTS one_row_table
(
    one_row INT          NOT NULL DEFAULT 1,
    id      varchar(255) NOT NULL
);

CREATE UNIQUE INDEX one_row_only_uidx_one_row_table ON one_row_table (( true ));

insert into one_row_table (id) values ('2');

insert into one_row_table (id) values ('3') ON CONFLICT (one_row) DO UPDATE SET id = EXCLUDED.id;

在最后一次插入时,我得到ERROR: there is no unique or exclusion constraint matching the ON CONFLICT specification。有人能解释一下我在这里做错了什么吗?我该如何修复它?我搜索并查看了这里的文档https://www.postgresql.org/docs/current/sql-insert.html,但我仍然不明白这个问题。

mccptt67

mccptt671#

这一个工作,与一个生成的列,不能由用户设置:

CREATE TABLE IF NOT EXISTS one_row_table ( 
        one_row BOOL GENERATED ALWAYS AS ( TRUE ) STORED
    , ID VARCHAR ( 255 ) NOT NULL 
);
CREATE UNIQUE INDEX one_row_only_uidx_one_row_table ON one_row_table ( ( one_row ) );

INSERT INTO one_row_table ( ID ) VALUES ( '2' ) 
ON conflict ( one_row ) DO
UPDATE 
    SET ID = EXCLUDED.ID 
RETURNING *;

INSERT INTO one_row_table ( ID ) VALUES ( '3' ) 
ON conflict ( one_row ) DO
UPDATE 
    SET ID = EXCLUDED.ID RETURNING *;
    
-- fails because of the manual setting for "one_row":   
INSERT INTO one_row_table ( one_row, ID ) VALUES    (false, '1' ) 
ON conflict ( one_row ) DO
UPDATE 
    SET ID = EXCLUDED.ID 
RETURNING *;

相关问题