如何在数据库中创建关系

How to create relationship in DB

我必须创建三个 tables ACCOUNTING_POINT 作为 AP,METER_CHANGE 作为 MC,和 METER 作为 M table MC 将 AP 与 M 结合,但我应该确保 M.id 在从 AP 到 MC 的行中是唯一的。所以我应该确定 AP 永远不会引用某些具有相同 M.id 的 MC。它看起来像这样:

这里有一张描述我的问题的图片红行表示问题

我知道我可以在 table MC 中使用属性“actual”并创建 pk_meter_id_actual = unique,但我想避免使用此属性。我应该为历史保留 MC.ap_id,为连接保留 AP.meter_change

It looks like this:

我通过在 table MC 和两个约束中添加布尔属性“实际”来解决它: CREATE UNIQUE INDEX meter_id ON MC (meter_id, actual) WHERE (actual is true); CREATE UNIQUE INDEX ap_id ON MC (ap_id, actual) WHERE (actual is true);