postgresql - 有没有办法为 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
);
google_subscription
正在fk_customer_id
引用customer
tableid
。apple_subscription
正在fk_customer_id
引用customer
tableid
。
我想知道,是否有可能创建一个约束,例如customer
table id
,只能在google_subscription
or中找到apple_subscription
,但不能在两者中找到?
解决方案
不,那是不可能的。一个约束不能跨越多个表。相反,您可以拥有另一个表subscriptions
,您可以在其中拥有唯一索引customer(id)
。或者,您可以在客户表中设置另一列,该列一次仅包含 1 个订阅。
推荐阅读
- android - 如何在 Kotlin 中使用 MutableLiveData?
- sql - 将单引号添加到动态 SQL
- python - 我如何遍历以逗号分隔的字符串中的每个条目,并使用 Python 将其作为单独的输入包含在内
- sql - 如何在查询中获取单行 SELECT FOR UPDATE
- simulation - Anylogic,如何动态更改生产批次的大小?
- tsql - TSQL For XML JSON AUTO 使用 CTE 和 UNION 生成平面结果
- php - 数组查询 - 转换此数组的最有效方法是什么?
- python - 增加自动缩放组的最大大小的 Lambda 问题
- javascript - 我需要推荐结构以使用 Cytoscape js
- office-js - 如何将 Office displayDialogAsync 与 oauth 库一起使用