简体   繁体   中英

Is there a way to create a unique constraint for 2 tables?

Currently, I have the following 3 tables.

CREATE TABLE customer (
    id SERIAL PRIMARY KEY
);

CREATE TABLE google_subscription (
    fk_customer_id INTEGER NOT NULL UNIQUE,

    CONSTRAINT fk_customer_id_constraint
        FOREIGN KEY(fk_customer_id) 
        REFERENCES customer(id)
        ON DELETE RESTRICT
);

CREATE TABLE apple_subscription (
    fk_customer_id INTEGER NOT NULL UNIQUE,

    CONSTRAINT fk_customer_id_constraint
        FOREIGN KEY(fk_customer_id) 
        REFERENCES customer(id)
        ON DELETE RESTRICT
);
  1. google_subscription is having fk_customer_id referencing to customer table id .
  2. apple_subscription is having fk_customer_id referencing to customer table id .

I was wondering, is it ever possible to create a constraint, such that customer table id , will only be found in either google_subscription or apple_subscription , but NOT both?

No that is not possible. A constraint cannot span across multiple tables. Instead you can have another table subscriptions where you can have a unique index on customer(id) . Or you can have another column in customer table which will hold only 1 subscription at a time.

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