Skip to content
Advertisement

PostgreSQL : how to query from 3 tables (with 1 junction table)?

table ‘product’

Junction table ‘ingredient_product’

table ‘ingredient’

I have 3 tables and tried to query like below

and I get the result like below

I get the all different ingredients but wanted to show only once for the duplicates.

is there better way to query this type?

Thank you in advance!

Advertisement

Answer

You seem to want aggregation, something like this:

Notes:

  • Table aliases make the query easier to write and read.
  • The WHERE clause filters on the primary key of product rather than on the equivalent column in ingredient_product. I think that primary keys may help the optimizer.
  • This adds a GROUP BY, because you want one row per product. This is aggregating by the primary key, so the SELECT can contain other columns.
  • The array_agg() brings the ingredients together as an array.
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement