Let's say we want to use globally unique id and find the type of entity using it:
CREATE TABLE identity (
id serial PK NOT NULL,
type IdentityEnum NOT NULL,
UNIQUE (id, type)
);
CREATE TABLE user (
id integer PK NOT NULL REFERENCES identity (id),
type IdentityEnum NOT NULL,
UNIQUE (id, type)
ALTER TABLE user
add constraint identity_fk
foreign key (id, type)
REFERENCES identity (id, type);
);
CREATE TABLE animal (
id integer PK NOT NULL REFERENCES identity (id),
type IdentityEnum NOT NULL,
UNIQUE (id, type)
ALTER TABLE animal
add constraint identity_fk
foreign key (id, type)
REFERENCES identity (id, type);
);
To ensure that user or animal tables will have one to one relation to identity:
- it's will not be possible by more that one table to point at the same
identityPK
We are forced to add additional type column for each table, add UNIQUE (id, type) and add FK from each table to identity.
Questions:
- Is there another way to design database with a shared by multiple tables
idwithout the need fortype? - How to do joins if you have only id and don't know the type?