I
I
Ivan Huk2020-09-25 11:34:10
PostgreSQL
Ivan Huk, 2020-09-25 11:34:10

How to get all unique records from the database?

There are 2 tables: products and product_prices , they are linked by the key products.id = product_prices.product_id

And the query:

SELECT DISTINCT ON ( product_prices.product_id) product_id, slug, city_id 
FROM"products"
  LEFT JOIN "product_prices" ON "product_prices"."product_id" = "products"."id" 
ORDER BY city_id asc LIMIT 30


The problem is that I need to do order by city_id asc

Instead of sorted records, I get an error:
ERROR: SELECT DISTINCT ON expressions must match initial ORDER BY expressions

When I add product_id, city_id asc to ORDER BY, it sorts by product_id

How to solve such a problem?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Melkij, 2020-09-25
@melkij

distinct on requires using order by on the same fields and some other criteria for determining the "first" row.
If you need some other sorting as a result of the entire query that does not match this one, wrap the query in a subquery and resort as needed again.
select ... from (...) subquery order by ...

T
TyuReal, 2020-09-26
@TyuReal

"When I add to ORDER BY product_id, city_id asc it sorts by product_id"
ORDER BY city_id asc, product_id did not try? :)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question