I have a table in a Postgres 12 database with that has an array column with a bunch of dog breed guids. I want to lookup these values and basically return the lookup values instead of the guids.
CREATE TABLE dogs(
name text,
breeds text[]
);
INSERT INTO dogs (name, breeds) VALUES ('Barkley', '{"abc", "xyz"}');
INSERT INTO dogs (name, breeds) VALUES ('Ponyo', '{"zzz", "xyz"}');
CREATE TABLE breeds(
guid text,
breed text
);
INSERT INTO breeds (guid, breed) VALUES ('abc', 'Maltipoo');
INSERT INTO breeds (guid, breed) VALUES ('xyz', 'Jack Russel');
INSERT INTO breeds (guid, breed) VALUES ('zzz', 'Dalmatian');
I would like to be able to return the following:
Barkley, ['Maltipoo', 'Jack Russel']
Ponyo, ['Jack Russel', 'Dalmatian']
Essentially, look them up in my 'breeds' table before returning the values. Order of elements is not relevant.
LEFT JOIN LATERAL (…) ON truelooks weird. Is there any reason one would prefer this over putting the subquery directly into theSELECTexpressions? – Bergi Jul 06 '21 at 09:09SELECT d.name, array_agg(b.breeds_text) FROM dogs d LEFT JOIN unnest(breeds) a(guid) JOIN breeds b USING (guid) GROUP BY d.nameas an alternative, although that approach has weird edge cases with empty arrays – Bergi Jul 06 '21 at 09:11LEFT JOIN LATERAL (...) ON truemakes sense to keep all rows to the left in the result if the right table expression does not return any rows. Since that cannot actually happen in this case, I switched to a simplerCROSS JOINnow. (Equivalent in this case.). Generally, a correlated subquery is equivalent toLEFT JOIN LATERAL (...) ON true, but the latter is more versatile. (Allows various join types, join conditions, and it can return multiple columns.) It's not needed in this particular query. So I also suggested the simpler correlated subquery. – Erwin Brandstetter Jul 06 '21 at 22:41SELECT, which have to be aggregated back correctly and for a price. Simple in the example. Typically, there are more columns and it's not as simple. – Erwin Brandstetter Jul 06 '21 at 22:53WHERE b.breed = 'Dalmatian'in the sub-query does not work. – dylankb Aug 12 '22 at 05:07