Home > Software engineering >  Is there a better way to return a table that has a one-to-many relationship
Is there a better way to return a table that has a one-to-many relationship

Time:12-11

I am wanting to have my data in a better format so my front-end application can be more efficient if possible. Currently, I am using Postgres and I have a table that contains a one-to-many relationship and after I join my tables, I get multiple rows with mainly repeated data just to show the different 'many' values it has (obviously). Is there any possible way to make it so the 'many' values are put into an array so I don't get so many extra rows or if not, what would be the most efficient way to process the data returned from a one-to-many relationship in the front-end?

Example:

"name" | "attributes"

"Shirt" | "Medium"

"Shirt" | "Red"

Would it be possible to instead get a result like this so that it is easier to process on the front-end: "name" | "attributes"

"Shirt" | ["Medium", "Red"]

CodePudding user response:

You are looking for the Aggregate Functions array_agg or string_agg.

select name, array_agg(attribute) attributes
  from example 
 group by name;

See demo

  • Related