N
N
Nikita Dergachov2017-10-17 13:20:15
MySQL
Nikita Dergachov, 2017-10-17 13:20:15

How to write a request to get the N most populated cities?

The database (MySQL) has 2 tables for storing cities and users living in them:

city(id, name);
user(id, name, city_id);

Write an SQL query that will return at most N most populated cities with the name and number of users. The list must contain only cities with at least M users. The list must be sorted by the number of users in descending order, starting with the most populated city. If multiple cities have the same number of users, those cities in the sample should be sorted alphabetically.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Alex-1917, 2017-10-17
@alex-1917

Firstly, it was not completely copied from the training manual))) There should also be a table or column in the table where the data on the population itself is actually)))
Secondly, the author, if your task sounds like this:
then here is my answer and solution to the question:
UPD. Oh sent, thanks! Right now I'll sketch by hand)))
The first part:

SELECT * FROM city, user WHERE (тут будет вторая часть кода) LIMIT $n

M
Maxim Fedorov, 2017-10-17
@Maksclub

Just by analogy + add sorting and limit:
www.sql.ru/forum/749635/podskazhite-s-count-v-svya...
In general, study the possibilities of Google - it helps
while you are a web programmer - this means that there are giant search engines and there is the Internet
UPD: and yes, it is better not to do such questions under "I'm looking for a job"

T
tgnwest, 2017-11-02
@tgnwest

Something like that

SELECT city.name city_name, COUNT(user.id) users FROM city LEFT JOIN user ON city.id = user.city_id GROUP BY city.name HAVING users >= M ORDER BY users DESC, city_name ASC LIMIT N

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question