A
A
Alexander2016-02-15 19:57:24
MySQL
Alexander, 2016-02-15 19:57:24

SELECT with unknown nesting?

Hey!
There is one geo table with cities, regions, districts, countries (id, type, name, id_parent).
Example:

1 | country  | Россия       | 0
2 | district | Крым         | 1
2 | area     | Большая Ялта | 2
3 | city     | Массандра    | 3

PS Nesting is not always 4-level, it can be just "country-city" or "country-region-city".
How to write a query that will select all cities given the country ID?

Answer the question

In order to leave comments, you need to log in

4 answer(s)
A
Alexander, 2016-02-15
@librown

Made through three UNION.

M
mletov, 2016-02-15
@mletov

1) In practice, it often happens that there is no need for a universal solution, since it is known that the nesting depth cannot exceed a certain reasonable value.
2) If nevertheless it is necessary universally... In MS SQL there is a convenient piece, CTE. There is nothing like this in MySql, so google "mysql recursive query"
3) Alternatively, write a stored function and use a cursor in it

M
Marat, 2016-02-15
@Joysi75

Is mysql critical? Some DBMS have types for storing tree structures.
For example MSSQL (express free version) - https://msdn.microsoft.com/en-us/library/bb677290.aspx
or an overview here https://habrahabr.ru/post/27774/

R
res2001, 2016-02-15
@res2001

I would split this one big table into several (countries, towns, streets/avenues/..., houses/apartments). It will be much easier to work and get rid of a lot of nesting.
Take KLADR as an example.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question