Sample Header Ad - 728x90

Design of a table that references several columns in two other tables

2 votes
1 answer
69 views
Is it possible to create a table that is built from an inner join of two other tables with additional columns, but where the rows are kept updated when the inner join is re-run? Currently using postgresql 17. So far I have the following tables:
CREATE TABLE public.outcomes (
    id integer NOT NULL,
    paper_id integer NOT NULL,
    outcome text NOT NULL
);


CREATE TABLE public.papers (
    id integer NOT NULL,
    paper_id text NOT NULL
);


CREATE TABLE public.predictors (
    id integer NOT NULL,
    paper_id integer NOT NULL,
    predictor text NOT NULL
);


COPY public.outcomes (id, paper_id, outcome) FROM stdin;
1	1	outcome 1
2	1	outcome 2
3	2	outcome 3
\.


COPY public.papers (id, paper_id) FROM stdin;
1	paper a
2	paper b
\.


COPY public.predictors (id, paper_id, predictor) FROM stdin;
1	1	predictor 1
2	1	predictor 2
3	2	predictor 1
4	2	predictor 2
\.


ALTER TABLE ONLY public.outcomes
    ADD CONSTRAINT outcomes_pkey PRIMARY KEY (id);


ALTER TABLE ONLY public.papers
    ADD CONSTRAINT papers_pkey PRIMARY KEY (id);


ALTER TABLE ONLY public.predictors
    ADD CONSTRAINT pk_predictors PRIMARY KEY (id);


ALTER TABLE ONLY public.outcomes
    ADD CONSTRAINT outcomes_paper_fkey FOREIGN KEY (paper_id) REFERENCES public.papers(id);


ALTER TABLE ONLY public.predictors
    ADD CONSTRAINT predictors_paper_fkey FOREIGN KEY (paper_id) REFERENCES public.papers(id);
I have tried creating a materialized view based on a query that joins all three tables, and I can create triggers to refresh the materialized view when the outcomes or predictors tables are added to.
select pa.paper_id, ou.outcome, pr.predictor
from predictors pr
inner join outcomes ou on ou.paper_id = pr.paper_id 
inner join papers pa on pa.id = ou.paper_id;
But I can't find a way to create a table from this query that: - lets me add new rows to the child table when I add rows to either the outcomes or predictors tables, and - lets me store new data in additional columns |paper_id|outcome |predictor | new column here | |--------|---------|-----------|-----------------| |paper a |outcome 1|predictor 1| |paper a |outcome 2|predictor 1| |paper a |outcome 1|predictor 2| |paper a |outcome 2|predictor 2| |paper b |outcome 3|predictor 1| |paper b |outcome 3|predictor 2| Any pointers or suggestions of what to investigate welcomed.
Asked by brendans-bits (23 rep)
Sep 15, 2025, 02:04 AM
Last activity: Sep 16, 2025, 04:09 PM