I have two tables with the following information
PRODUCTS
id |description |featureImage
13 |a phone | www.image.com/image23
14 |a phone accessory | www.image.com/image24
15 |another accessory | www.image.com/image25
Product Accessories
id |productId |accessoryId
1 |13 |14
2 |13 |15
When using a query as follows
SELECT DISTINCT ON (accessories.id, products.description)
products.description, products.featureImage, accessories.id
FROM schema.accessories
JOIN schema.products ON products.id IN
(SELECT accessories.accessoryId FROM accessories
WHERE accessories.id IN (14,15))
I am getting duplicate results as
description |featureImage |id
a phone accessory |image.com/image24|14
a phone accessory |image.com/image24|15
another accessory |image.com/image25|14
another accessory |image.com/image25|15
The result set I was expecting would be
description |featureImage |id
a phone accessory |image.com/image24|14
another accessory |image.com/image25|15
So I would search the table for products with the original product id, and then get the ids of the rows with accessories for that product. Once I get those they are used for the sub query
(SELECT accessories.accessoryId FROM accessories WHERE accessories.id IN (14,15))
to get the results.
I was thinking that using the DISTINCT ON would stop the duplicates, but I am still getting duplicates, with the id being linked up incorrectly on some of them.
Question is solved, just need to wait for the 8 hours so I can reply and close as answered with the following text;
as per @a_horse_with_no_name by simplifying the query to
SELECT p.description, p.featureimage, a.accessory_id
FROM accessories a
JOIN products p ON p.id = a.accessory_id
with a Where statement at the end identifying the proper product to find accessories for, the expected result set is returned.
DISTINCT ON (accessories.id)returns me a result set with the appropriate different ids, but the description, and featureImage both come back as 'phone acessory' with its featureImage url.distinct ononly makes sense if you also use anorder by. But your join condition looks pretty strange as well. What exactly are you trying to achieve here?accessory.accessoryId = product.id