Answer the question
In order to leave comments, you need to log in
SQL: Query to select records grouped by parent?
Hello,
The task is as follows:
In the real estate market, there are both "loner" objects (for example, infill development, only one house), and groups of objects (a residential complex with a bunch of buildings, a cottage village with towns, plots).
For each object (building, townhouse in the village, cottage in the village, etc.) there is a record in the table.
For those objects that are included in the group (RC, village, etc.), there is an additional parent record, and the relationship between them is built by parent_id in the same table.
Example:
id | parent_id | object_type | ...
----------------------------------------------
1 | 0 | common | ...
2 | 0 | newflats | ...
3 | 1 | newflats | ...
4 | 1 | newflats | ...
5 | 0 | cottage | ...
SELECT * FROM objects WHERE object_type!='common' AND ....
id | parent_id | object_type | ...
-----------------------------------------------
7 | 0 | newflats | ...
3 | 1 | newflats | ...
4 | 1 | newflats | ...
2 | 0 | newflats | ...
id | parent_id | object_type | ...
-----------------------------------------------
7 | 0 | newflats | ...
3 | 1 | newflats | ...
2 | 0 | newflats | ...
Answer the question
In order to leave comments, you need to log in
The dumbest option is to make a distinct selection where parent_id > 0 and then merge
with a selection where parent_id = 0.
I can also add that despite the bags, it was necessary to throw out scripts for creating and filling tables, you would have written a query in about 7 minutes, not more.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question