首页 > 解决方案 > 有没有办法为 2 个表创建唯一约束?

问题描述

目前,我有以下 3 个表。

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正在fk_customer_id引用customertable id
  2. apple_subscription正在fk_customer_id引用customertable id

我想知道,是否有可能创建一个约束,例如customertable id,只能在google_subscriptionor中找到apple_subscription,但不能在两者中找到?

标签: postgresql

解决方案


不,那是不可能的。一个约束不能跨越多个表。相反,您可以拥有另一个表subscriptions,您可以在其中拥有唯一索引customer(id)。或者,您可以在客户表中设置另一列,该列一次仅包含 1 个订阅。


推荐阅读