简体   繁体   中英

SQL: Order by a list of foreign_key numbers

A simplified example:

I have a SQL table called things . Things by themselves have an id and a name . Things are part of a tree, eg a thing can have a parent; Exactly how to this is stored is not important, important is however that it is possible to obtain a list of thing ids from the root node to the current thing.

I have another table, called properties . A property has a thing_id column, a name column and a value column.

I now want, for the current thing, to obtain all properties, ordered by thing_id, in order of the paths from root thing to current thing .

eg, if the current thing is nested like this: Root(1) > Vehicle(4) > Car(2) > Hybrid(3) , I would want the list of properties be returned with the properties that have a thing_id==1 first, followed by the ones with thing_id == 4 , then thing_id==2 and finally thing_id==3 .

How can this be done using SQL? (without using N+1 selects)

In SQL this can be achieved with use of recursive query. Here is an example

DECLARE @item as varchar(10) 

with CTE (main_part, sub_part, NestingLevel) 
as    
( 
                select main_part, sub_part, 1 from tblParts 
                        where main_part = @item 

                union all 

                select tblParts.main_part, tblParts.sub_part, (NestingLevel + 1) from tblParts 
                inner join CTE on tblParts.main_part = CTE.sub_part 
) 

select * from CTE 

In order to address this in MySQL you can try temporary table approach. Here is a good example of it: How to do the Recursive SELECT query in MySQL?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM