I would like to perform a FULL OUTER JOIN ON a condition that is an integer being in an array of integer.
The query would look something like this:
SELECT thing FROM table1 t1 FULL OUTER JOIN table2 t2 ON t1.id = ANY(t2.array_of_ids)
But I get the following error:
FULL JOIN is only supported with merge-joinable or hash-joinable join conditions
Is there a way to make this condition merge-joinable ?
Advertisement
Answer
Hmmm . . . Does it work like this?
SELECT thing FROM table1 t1 FULL OUTER JOIN (table2 t2 CROSS JOIN UNNEST(t2.array_of_ids) t2_id ) ON t1.id = t2_id;
The issue with this is that it will multiply the number of rows. So, how about just constructing the FULL JOIN
?
SELECT . . . FROM table1 t1 LEFT JOIN (table2 t2 CROSS JOIN UNNEST(t2.array_of_ids) t2_id ) ON t1.id = t2_id UNION ALL SELECT . . . FROM table2 t2 WHERE NOT EXISTS (SELECT 1 FROM UNNEST(t2.array_of_ids) t2_id JOIN table1 t1 ON t2_id = t1.id );