简体   繁体   English

如何引用具有多个主键的 postgres 表

[英]How to reference a postgres table with multiple primary keys

How could I create a xref table with a reference to this table?如何创建一个引用该表的外部参照表?

CREATE TABLE reviewer (
  screen_name integer,
  identity_provider text
  CONSTRAINT identity PRIMARY KEY (screen_name, identity_provider)
);

This is what I've tried so far:这是我迄今为止尝试过的:

CREATE TABLE business_reviewer_xref (
  reviewer_screen_name integer,
  reviewer_identity_provider text,
  CONSTRAINT reviewer_identity UNIQUE (reviewer_screen_name, reviewer_identity_provider),
  reviewer_identity REFERENCES reviewer(identity)
);
CREATE TABLE business_reviewer_xref (
  reviewer_screen_name integer,
  reviewer_identity constraint REFERENCES reviewer(identity)
);
CREATE TABLE business_reviewer_xref (
  reviewer_screen_name integer,
  reviewer_identity REFERENCES reviewer(identity)
);

A table cannot have multiple primary keys.一个表不能有多个主键。 It can only have one or none.它只能有一个或没有。 But a primary key can of course consist of more than one column (but at least of one of course).但是主键当然可以包含多于一列(当然至少包含一列)。 To reference such a multi column primary key, you need a corresponding column in the referencing table for each column in the primary key of the referenced column.要引用这样的多列主键,您需要为被引用列的主键中的每一列在引用表中对应一个列。

To define a foreign key constraint, list the corresponding columns in the referencing table in the same order as their counterparts occur in the primary key constraint in the referenced table in the defining tuple of the foreign key.要定义外键约束,请按照外键定义元组中引用表中主键约束中的对应列出现的顺序列出引用表中的相应列。 Also keep the order in the definition of the referenced columns' tuple.还要保持引用列的元组定义中的顺序。

In your case:在你的情况下:

CREATE TABLE business_reviewer_xref
             (reviewer_screen_name integer,
              reviewer_identity text,
              FOREIGN KEY (reviewer_screen_name,
                           reviewer_identity)
                          REFERENCES reviewer
                                     (screen_name,
                                      identity));

Note that a foreign key constraint, in contrast to a primary key constraint, doesn't implicitly set a unique constraint.请注意,与主键约束相比,外键约束不会隐式设置唯一约束。 If you want uniqueness too, you'd have to define another constraint for that.如果您也想要唯一性,则必须为此定义另一个约束。

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

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