SQL select descendants of a row

走远了吗. 提交于 2019-12-05 12:00:26

Some databases allow that using recursive common table expressions, but not SQLLite.

You could consider changing your table definition. With a table like this, it's easy to query all descendants of 1:

id (varchar)
--------------
001
001002
001002003
001002003004
001002003005
001002006

This allows you to query all descendants of 1 like:

select * from YourTable where id like '001%'

It sounds a bit whacky, but works very well in practice.

Dean Harding

The way you've set up your schema doesn't really suit itself very well to the relational model (as you've discovered). But there is another way that may not be so obvious at first, but is much more flexible. It's called a "nested set model" and it just structures things slightly differently.

Managing Hierarchical Data in MySQL (look for the section "The Nested Set Model") shows how to do this in MySQL, but it should translate to SQLite fairly easily. I won't go into too much detail here, because that article is actually pretty long, but it should give you all you need to get going.

Oracle has a CONNECT BY syntax that could be used for this, but of course it's specific to oracle.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!