开发者

How order results of SQL request according hierarchy level

开发者 https://www.devze.com 2023-01-19 16:17 出处:网络
I the context of a Java application I am using SQLIte to persist some data. One of my SQL table has the following structure

I the context of a Java application I am using SQLIte to persist some data. One of my SQL table has the following structure

CREATE TABLE containers (ID INT PRIMAR开发者_如何转开发Y KEY, NAME TEXT, PARENT_ID INT)

I need to retrieve all the containers ORDERED by hierarchy level. I.e I want first all the containers without parent (PARENT_ID == -1), then the ones with 1 ancestor, then with 2 ancestors, etc ....

Is there any way to do that with an SQL request such as below to have a ResultSet object sorted in this way.

SELECT * from container ORDER BY (**"What to put here ???"**)

Edit I know I can do that in Java later but I am not interested in this solution.


There isn't a way to achieve this directly in standard SQL. Oracle has the "start with", "connect by" syntax and that supports it through "level".

Alternatively, if you can remodel your data you could instead use nested sets: http://en.wikipedia.org/wiki/Nested_set_model

0

精彩评论

暂无评论...
验证码 换一张
取 消