0

I have a Product model that has many Skus, and each product can also have a Customization that includes being featured. Schema looks like this:

Product
| id | category_id | title | image |

Sku
| id | product_id | subtitle | price |

Customization
| id | product_id | title | featured |

I'm filtering/sorting the Product based on its category_id and the prices of its Skus like so:

SELECT id, title, image, prices
  FROM (
    SELECT p.id, p.title, p.image, array_agg(s.price) as prices
    FROM "Products" p
    JOIN "Skus" s
    ON p.id = s.product_id
    WHERE p.category_id in (1,2,3,4) AND s.price > 99
    GROUP BY p.id
  ) x
ORDER BY id DESC;

I'd like to add an additional filter for Products whose Customizations have featured = true.

Is it possible to include another JOIN to do this, or is there a better approach?

1 Answer 1

2

First, you don't need the subquery. Second you can do this with a JOIN (or IN or EXISTS):

SELECT p.id, p.title, p.image, array_agg(s.price) as prices
FROM "Products" p JOIN
     "Skus" s
      ON p.id = s.product_id JOIN
      Customization c
      ON p.id = c.product_id AND c.featured = true
WHERE p.category_id in (1, 2, 3, 4) AND s.price > 99
GROUP BY p.id
ORDER BY p.id DESC
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, this works great and improves my original query as well!

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.