0

Could anyone help me while running query in Postgresql. I'm getting a duplicate record.

SELECT a.id, b.parameter_id
FROM products a
LEFT JOIN products_parameters b ON b.product_id = a.id 
WHERE a.category_id = 14 AND b.parameter_id = 22
ORDER BY a.id

Result - duplicated rows:

enter image description here

My data from table products:

SELECT *
FROM "products"
WHERE "id" = '10'

enter image description here

My data from table products_parameters:

SELECT *
FROM "products_parameters"
WHERE "product_id" = '10'

enter image description here

What is wrong with my query?

1 Answer 1

1

If you don't want duplicates, the simplest solution is to use select distinct:

SELECT DISTINCT p.id, pp.parameter_id
FROM products a JOIN
     products_parameters pp
     ON pp.product_id = p.id 
WHERE p.category_id = 14 AND pp.parameter_id = 22
ORDER BY p.id;

Your question doesn't have enough information to specify why you are getting duplicates, but presumably because you are only choosing one column from each of the tables and other columns are different.

Note the other changes to the query:

  • The table aliases are meaningful rather than arbitrary letter.
  • The WHERE clause turns the LEFT JOIN into an inner join anyway, so this version properly expresses the JOIN.
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for your response. Query not duplicate rows with DISTINCT, but i didn't understand why this rows duplicates :)

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.