我在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),
);
如果我用外键调用它,那么它应该是一个值:
foreign key (var_key_f) references Test(var_key),
编辑:我知道两个多主键条目的选项,但我想只有一个主键,所以我不必再引用两个变量。我需要将两个变量生成一个主键。
答案 0 :(得分:0)
看来这可以在没有触发器的情况下完成:(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
结果:
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".