PostgreSQL
 sql >> Datenbank >  >> RDS >> PostgreSQL

Unique Constraint über mehrere Tabellen

Sie könnten Folgendes versuchen. Sie müssen eine redundante UNIQUE-Einschränkung für (id, aId) erstellen in Parent (SQL ist ziemlich dumm, nicht wahr?!).

CREATE TABLE Child
(parentId INTEGER NOT NULL,
 aId INTEGER NOT NULL UNIQUE,
FOREIGN KEY (parentId,aId) REFERENCES Parent (id,aId),
createdOn TIMESTAMP NOT NULL);

Möglicherweise wäre es eine viel bessere Lösung, parentId ganz aus der Child-Tabelle zu entfernen und bId hinzuzufügen stattdessen und verweisen Sie einfach auf die übergeordnete Tabelle basierend auf (aId, bId) :

CREATE TABLE Child
(aId INTEGER NOT NULL UNIQUE,
 bId INTEGER NOT NULL,
FOREIGN KEY (aId,bId) REFERENCES Parent (aId,bId),
createdOn TIMESTAMP NOT NULL);

Gibt es einen Grund, warum Sie das nicht tun können?