简体   繁体   English

在创建表的主键中添加PostgreSQL

[英]PostgreSQL Addition in Primary Key in Create Table

i'm facing a problem with a primary key in PostgreSQL, my plan was to make an addition of two values and set this to one primary key, how could this be realized (first try below): 我在PostgreSQL中遇到主键问题,我的计划是将两个值相加并将其设置为一个主键,如何实现(首先尝试以下操作):

/* Tabelle fuer die Test*/  
create table Test(
var_a integer,
var_b integer,
var_key integer,
var_key = var_a + var_b,
primarykey(var_key),
);

if i call this with a foreign key then it should be one value: 如果我用外键调用它,那么它应该是一个值:

foreign key (var_key_f) references Test(var_key),

EDIT: I know th option of two multiple primary keys entries but i want to have only one primary key, so that i not have to reference over two vars again. 编辑:我知道两个多个主键条目的选项,但我只希望有一个主键,这样我就不必再次引用两个var。 I need to have both variables generated to one primary key. 我需要将两个变量都生成到一个主键。

It appears this can be accomplished without triggers: (pg-9.3): 看来这可以在没有触发器的情况下完成:(pg-9.3):

DROP SCHEMA tmp CASCADE;
CREATE SCHEMA tmp ;
SET search_path=tmp;

CREATE TABLE test
        ( var_key INTEGER NOT NULL PRIMARY KEY
        , var_a INTEGER NOT NULL
        , var_b INTEGER NOT NULL
        , var_key_f INTEGER REFERENCES test(var_key)
        , CONSTRAINT the_sum CHECK (var_a+var_b = var_key)
        );

INSERT INTO test(var_key, var_a, var_b) VALUES(42, 21, 21); -- Ok
INSERT INTO test(var_key, var_a, var_b) VALUES(666, 660, 6); -- Ok

INSERT INTO test(var_key, var_a, var_b) VALUES(34, 21, 11); -- bad sum
INSERT INTO test(var_key, var_a, var_b) VALUES(666, 600, 66); -- duplicate sum

INSERT INTO test(var_key, var_a, var_b, var_key_f) VALUES(14, 6, 8, 42); -- Ok
INSERT INTO test(var_key, var_a, var_b, var_key_f) VALUES(13, 5, 8, 43); -- Bad FK

Result: 结果:

NOTICE:  drop cascades to table tmp.test
DROP SCHEMA
CREATE SCHEMA
SET
CREATE TABLE
INSERT 0 1
INSERT 0 1
ERROR:  new row for relation "test" violates check constraint "the_sum"
DETAIL:  Failing row contains (34, 21, 11, null).
ERROR:  duplicate key value violates unique constraint "test_pkey"
DETAIL:  Key (var_key)=(666) already exists.
INSERT 0 1
ERROR:  insert or update on table "test" violates foreign key constraint "test_var_key_f_fkey"
DETAIL:  Key (var_key_f)=(43) is not present in table "test".

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM