SQL tree traversal

前端 未结 3 1594
抹茶落季
抹茶落季 2020-12-18 11:12

I am not totally sure I am naming this right, but please bear with me.

I am wondering if is possible to do something like this in SQL(MySQL specifically): Let\'s say

相关标签:
3条回答
  • 2020-12-18 11:35

    I was just asking myself the same question. This is what i googled: http://moinne.com/blog/ronald/mysql/manage-hierarchical-data-with-mysql-stored-procedures

    It works with stored procedures.

    But so much logic in the DB is not a good thing in my opinion..

    0 讨论(0)
  • 2020-12-18 11:40

    You're probably better of with the nested set model instead (see http://mikehillyer.com/articles/managing-hierarchical-data-in-mysql/ - further down). Its far more efficient for selects and you can get the complete path to each node with a simple self join. However, in practice it is a good idea to pre-cache path and depth if you want to do things like " where depth = 3" or want to show the complete path for multiple nodes if you have more than 1000 records in your table.

    0 讨论(0)
  • 2020-12-18 11:59

    It's possible to fetch all descendants utilizing solely SQL, but not in a single query. But I'm sure you figured that out; I assume you mean you want to do it in a single query.

    You might be interested in reading about some alternative designs to store tree structures, that do enable you to fetch all descendants using a single SQL query. See my presentation Models for Hierarchical Data with SQL and PHP.

    You can also use recursive SQL queries with other brands of database (e.g. PostgreSQL), but MySQL does not currently support this feature.

    0 讨论(0)
提交回复
热议问题