K
K
Kola2014-06-09 17:12:24
SQL
Kola, 2014-06-09 17:12:24

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 	| ...

When searching for objects, the user is presented with a selection of objects from the table according to specified conditions (by price, area, distance, etc.), excluding parent cards, while in a certain sorting, for example, by price.
But since There can be 10-20 cases in one LCD, and all of them often meet the specified criteria at the same time, then they can occupy the entire first page of the issue.
An example of the current output:
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 	| ...

The essence of the task:
Modify the query so that if the record has a parent record (parent_id > 0), only one child record per parent (the first of all according to the specified sorting) remains in the output, and the rest are ignored.
Those. The output after changing the query should look something like this:
id 	| parent_id 	| object_type 	| ...
-----------------------------------------------
7 	| 0 		| newflats 	| ...
3 	| 1 		| newflats 	| ...   
2 	| 0 		| newflats 	| ...

Those. in the output there are 2 objects with parent_id = 1.
The first of them in the current sorting is with id=3.
So, you need to leave it, and ignore all subsequent ones with parent_id=1.
Here. Evening, coffee, bags under the eyes. I'm stupid. I ask for your help.
I dig while grouping on parent_id from a subquery with sorting. But somehow the stone flower doesn't come out

Answer the question

In order to leave comments, you need to log in

1 answer(s)
F
Fadmin, 2014-06-10
@Fadmin

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 question

Ask a Question

731 491 924 answers to any question