2

I have a products table, and a separate table that I'd like to store related products in which consists of two fields: create table related_products(id1 int, id2 int) and indexes placed on each field. This would mean that I'd have to search both id1 and id2 for a product id, then pull out the other id field which seems quite messy. (Of course, one product could have many related products).

Is there a better table structure for storing the related products that I could use in postgresql?

3
  • you mean that the product has many2many relation between its records Commented Apr 5, 2017 at 14:57
  • @Charif yes, that's right! Commented Apr 5, 2017 at 15:11
  • There no way to do it better this what you have to do Commented Apr 5, 2017 at 15:13

1 Answer 1

1

That is not messy from a database perspective, but exactly the way it should be, as long as only pairs of products can be related.

If you want to make sure that a relationship can be entered only once, you could use a unique index:

CREATE UNIQUE INDEX ON related_products(LEAST(id1, id2), GREATEST(id1, id2));

To search products related to product 42, you could query like this:

SELECT products.*
FROM products
JOIN (SELECT id2 AS id
         FROM related_products
         WHERE id1 = 42
      UNION ALL
      SELECT id1
         FROM related_products
         WHERE id2 = 42
     ) rel
   USING (id);
Sign up to request clarification or add additional context in comments.

2 Comments

is there a performance difference between using an explicit join and a select * from products p where id in((SELECT id1 FROM related_products WHERE id2 = 1 union all select id2 from related_products where id1 = 1));
Probably not - I usually prefer joins, but that's a matter of taste. Compare the plans and execution time to make your choice. Try with a) few result rows and b) many result rows in the UNION.

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.