Given 3 tables — e.g. posts
, comments
, and tags
— is there a way of having a foreign key in one of them referencing a primary key of one of the other two?
CREATE TABLE IF NOT EXISTS posts (
id UUID DEFAULT uuid_generate_v4 ()
CONSTRAINT posts_pk PRIMARY KEY
);
CREATE TABLE IF NOT EXISTS comments (
id UUID DEFAULT uuid_generate_v4 ()
CONSTRAINT comments_pk PRIMARY KEY
);
CREATE TABLE IF NOT EXISTS tags (
id UUID DEFAULT uuid_generate_v4 ()
CONSTRAINT tags_pk PRIMARY KEY
);
DROP TYPE IF EXISTS s_type;
CREATE TYPE s_type AS ENUM (
'POST',
'COMMENT'
);
CREATE TABLE IF NOT EXISTS tag_mentions (
id UUID DEFAULT uuid_generate_v4 ()
CONSTRAINT tag_mentions_pk PRIMARY KEY,
source_type s_type NOT NULL,
source_id UUID NOT NULL
CONSTRAINT tag_mention_id_fk
-- Is something like this possible?
REFERENCES posts (id) OR comments (id)
);
Maybe there's a way of doing this with a composite index between s_type
and posts
and comments
IDs?