In my database I have the following schema:
CREATE TABLE survey_results (
id integer NOT NULL
);
CREATE TABLE slide_results (
id integer NOT NULL,
survey_result_id integer,
tags character varying[] DEFAULT '{}'::character varying[],
content character varying,
created_at timestamp with time zone NOT NULL
);
INSERT INTO survey_results (id)
VALUES (1);
INSERT INTO slide_results (id, survey_result_id, tags, content, created_at)
VALUES (1, 1, '{food}', 'Food slide', now());
INSERT INTO slide_results (id, survey_result_id, tags, content, created_at)
VALUES (2, 1, '{motivation}', 'Motivation slide', now());
Now I want to have an SQL query that will return survey result id and content for slide results with specified tags. I wrote something like this:
select distinct on(sr.id)
sr.id,
slr.content AS food,
slr2.content AS motivation
from survey_results sr
LEFT JOIN slide_results slr ON slr.survey_result_id = sr.id AND slr.id IN (
SELECT id as id
FROM slide_results
WHERE 'food' = ANY(tags)
ORDER BY created_at desc
)
LEFT JOIN slide_results slr2 ON slr2.survey_result_id = sr.id AND slr2.id IN (
SELECT id as id
FROM slide_results
WHERE 'motivation' = ANY(tags)
ORDER BY created_at desc
)
group by slr.content, slr2.content, sr.id
which returns:
| id | food | motivation |
| --- | ---------- | ---------------- |
| 1 | Food slide | Motivation slide |
This query works fine, but I'm wondering if there is better way of doing this?
EDIT:
I forgot to add link do db-fiddle: