postgresql - Fetching distinct rows from multiple joins SQL -
i have 1 main table called deliveries , has 1 many relationship deliveries_languages dl, deliveries_markets dm , deliveries_tags dt having delivery_id foreign key. these 3 tables have 1 one relation languages , markets , tags respectively. additionaly, deliveries, table have 1 one relation companies , have company_is foreign key. following query have written:
select deliveries.*, languages.display_name, markets.default_name, tags.default_name, companies.name deliveries join deliveries_languages dl on dl.delivery_id = deliveries.id join deliveries_markets dm on dm.delivery_id = deliveries.id join deliveries_tags dt on dt.delivery_id = deliveries.id join languages on languages.id = dl.language_id join markets on markets.id = dm.market_id join tags on tags.id = dt.tag_id join companies on companies.id = deliveries.company_id deliveries.name ilike '%new%' , deliveries.created_by = '5f331347-fb58-4f63-bcf0-702f132f97c5' , deliveries.deleted_at null limit 10
here getting redundant delivery_ids because each delivery_id there multiple languages, markets , tags. want use limit on distinct delivery_ids. so, limit 10 should not give me 10 records above join query 10 records there distinct delivery_id (deliveries.id). can use derived table concept here not sure how can that. can please me resolve issue.
in postgres, can use distinct on
:
select distinct on (d.id) d.*, l.display_name, m.default_name, t.default_name, c.name deliveries d join deliveries_languages dl on dl.delivery_id = d.id join deliveries_markets dm on dm.delivery_id = d.id join deliveries_tags dt on dt.delivery_id = d.id join languages l on l.id = dl.language_id join markets m on m.id = dm.market_id join tags on t.id = dt.tag_id join companies c on c.id = d.company_id d.name ilike '%new%' , d.created_by = '5f331347-fb58-4f63-bcf0-702f132f97c5' , d.deleted_at null order d.id limit 10;
for larger amounts of data, can inefficient. multiple junction tables result in cartesian products when used this. however, smallish amount of data, should solve problem.
Comments
Post a Comment