how to prevent duplicates with inner join query (Postgres)
One way would be to use distinct
:
SELECT distinct "formulation_batch".*
FROM "formulation_batch"
INNER JOIN "formulation_batch_component"
ON "formulation_batch"."id" = "formulation_batch_component"."formulationBatch_id"
WHERE "formulation_batch"."project_id" = 1
AND (("formulation_batch_component"."component_id" = 2
OR "formulation_batch_component"."component_id" = 1 ))
In this case it is possible to apply the distinct
before the join
possibly making it more performant:
select fb.*
from
formulation_batch fb
inner join
(
select distinct formulationbatch_id
from formulation_batch_component
where component_id in (1, 2)
) fbc on fb.id = fbc.formulationbatch_id
where fb.project_id = 1
Notice how to use alias for the table names to make the query clearer. Also then in
operator is very handy. The use of double quotes with those identifiers is not necessary.