0

We have the two tables: "product" and "product_part". One product can have many product parts, so that the product_part has id_product column that refernces a product's id column.

I would really like to create a MATERIALIZED VIEW that from this data set:

| Product | Product Part|
+-----------------------+
| Gearbox | Metal scrap |
+-----------------------+
| Gearbox | Iron scrap  |
+-----------------------+
| Gearbox | Gold scrap  |
+-----------------------+

Would create this output:

| Product | Parts                                          |
+---------+------------------------------------------------+
| Gearbox | ["Metal scrap", "Iron scrap", "Gold scrap"]    |
+---------+------------------------------------------------+

1 Answer 1

1

This would just be:

SELECT product.name, json_agg(product_part.name) as parts
FROM product
JOIN product_part ON product.id = product_part.product_id
GROUP BY product.id, product.name;

I had to guess a bit about your actual columns, but this should be close.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. I think I may use it nicely to optimize app when combined with materialized views.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.