M
M
Max Yawo2015-09-03 21:57:08
Ruby on Rails
Max Yawo, 2015-09-03 21:57:08

How to get the number of related records in Postgresql?

Good day
In my Rails project there are cities and schools in them, that is:
there is a table cities
id | name
is tables schools
id | name | city_id
you need to display the cities table in descending order of the number of schools that are in each city, that is, do it in descending order of the number of schools, and cities in which there are no schools, do not receive at all
Thank you in advance.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
T
thepry, 2015-09-03
@Zlat1997

In the rails like this
Of course, the has_many :schools relationship must be put in the City. Or it is necessary to sort on SQL?
UPDATE: In SQL something like this:

City.joins('LEFT JOIN (SELECT city_id, count(id) AS counted_id FROM schools GROUP BY city_id) AS t2 ON cities.id = t2.city_id').order('COALESCE(counted_id, 0) DESC')

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question