V
V
Vanya Huk2018-06-20 15:24:59
PostgreSQL
Vanya Huk, 2018-06-20 15:24:59

How to fetch unique values ​​of a postgres column?

There are 2 tables, they are merged through join,
articles - fields id, model_id, city_id, region_id
models - id, name, brand_id
join occurs articles.model_id <-> models.id
Question - how to select only unique values ​​of the city_id field in the article table?
i need 3 fields from the first table select model_id, city_id, region_id, in that case i get an error

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
ViaCom, 2018-06-22
@ViaCom

1. Most likely you have an error in logic.
If most likely there can be SEVERAL models in one city (and theoretically regions, although it would not be logical), then you need to choose a SPECIFIC model.
2. Always Distinct use group by.

select max(model_id) as model_id, city_id, max(region_id) as region_id
from articles  a join models m on a.model_id = m.id 
group by  city_id

S
Stanislav B, 2018-06-20
@S_Borchev

It's not very clear what you want to get.
One line per city_id? region_id is clear - it is near city 1, but what about model_id?
And so about SELECT DISTINCT ON (city_id) city_id, region_id, blah blah blah FROM ...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question