简体   繁体   English

SQL:按外键数字列表排序

[英]SQL: Order by a list of foreign_key numbers

A simplified example: 一个简化的例子:

I have a SQL table called things . 我有一个名为things的SQL表。 Things by themselves have an id and a name . 事物本身具有idname 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. 确切的存储方式并不重要,但是重要的是可以获取从根节点到当前事物的事物ID列表。

I have another table, called properties . 我有另一个表,称为properties A property has a thing_id column, a name column and a value column. 一个属性具有一个thing_id列,一个name列和一个value列。

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 . 现在,对于当前事物,我想要获取按特性root到当前事物的路径顺序,按thing_id排序的所有属性。

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 . 例如,如果当前事物是这样嵌套的: Root(1) > Vehicle(4) > Car(2) > Hybrid(3) ,则我希望返回的属性列表中包含具有thing_id==1的属性首先,其次是thing_id == 4 ,然后是thing_id==2 ,最后是thing_id==3

How can this be done using SQL? 如何使用SQL完成此操作? (without using N+1 selects) (不使用N + 1个选择)

In SQL this can be achieved with use of recursive query. 在SQL中,这可以通过使用递归查询来实现。 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. 为了在MySQL中解决此问题,您可以尝试使用临时表方法。 Here is a good example of it: How to do the Recursive SELECT query in MySQL? 这是一个很好的例子: 如何在MySQL中进行递归SELECT查询?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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