简体   繁体   English

Postgresql 外键作为主键不唯一?

[英]Postgresql foreign key as primary not unique?

So i have a table, that takes a nickname as foreign key and a id to form a primary key:所以我有一个表,它需要一个昵称作为外键和一个 id 来形成一个主键:

CREATE TABLE Character(
    Nickname TEXT,
    CONSTRAINT person_pk PRIMARY KEY(Nickname)
);
CREATE TABLE POSTING(
    PostingID BIGINT UNIQUE, 
    Nickname TEXT,
CONSTRAINT posting_fk FOREIGN KEY(Nickname) REFERENCES Person(Nickname),
    CONSTRAINT postings_pk PRIMARY KEY(PostingID, Nickname)
);

So far, so good.到目前为止,一切都很好。 However, whenever i try to get now the primary key from posting, it tells me that: " there is no unique constraint matching given keys for referenced table "information"".但是,每当我现在尝试从发布中获取主键时,它都会告诉我:“没有唯一约束匹配引用表“信息”的给定键”。

CREATE TABLE INFORMATION(
    InformationID BIGINT,
    PostingID BIGINT, 
    CONSTRAINT informations_fk FOREIGN KEY(PostingID) REFERENCES POSTING(PostingID),
    CONSTRAINT informations_pk PRIMARY KEY(InformationID, PostingID)
);


CREATE TABLE DATA(
    InformationID BIGINT,
    Link TEXT NOT NULL,
    CONSTRAINT data_fk FOREIGN KEY(InformationID) REFERENCES INFORMATION(InformationID),
    CONSTRAINT datas_pk PRIMARY KEY(InformationID)
);

However, if i change in the table Information the InformationID to unique, the error disappears.但是,如果我在表信息中将 InformationID 更改为唯一,错误就会消失。 Is that the correct way of doing things?这是正确的做事方式吗?

CREATE TABLE INFORMATION(
    InformationID BIGINT UNIQUE,
    PostingID BIGINT,
    CONSTRAINT informations_fk FOREIGN KEY(PostingID) REFERENCES POSTING(PostingID),
    CONSTRAINT informations_pk PRIMARY KEY(InformationID, PostingID)
);

Thanks in advance everyone!提前谢谢大家!

Either the primary key for information should be only informationid , or data must include postingid and the foreign key to information is defined on both columns. informationid information或者data必须包含postingid并且information的外键在两列上都定义。

Hard to say without knowing your data, but I suspect the former solution to be the correct one.在不知道您的数据的情况下很难说,但我怀疑前一种解决方案是正确的。

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

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