My database has a table of Products, like so:
PRODUCTS
----------------------------
id | name | suppliers
----------------------------
1 | widget | {1,2}
2 | gizmo | {1}
3 | geegaw | {3}
4 | tchotchke | null
The suppliers
column contains an array (numeric[]
) of IDs belonging to a table of suppliers:
SUPPLIERS
------------
id | name
------------
1 | alpha
2 | beta
3 | gamma
How can I write a query that will return the contents of PRODUCTS
except with an array of supplier names instead of supplier ID numbers? Result should look like this:
-----------------------------------
id | name | suppliers
-----------------------------------
1 | widget | {'alpha','beta'}
2 | gizmo | {'alpha'}
3 | geegaw | {'gamma'}
4 | tchotchke | null
Succinct and efficient methods would be preferred, but readability/understandability are also nice.
Edit: This isn't a duplicate of the linked question, although that question does involve the unnest
operation, it doesn't re-aggregate the result. The answer to this question makes a new contribution to the site.