简体   繁体   中英

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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