What is the best practice for fetching a tree of nodes from database for further rendering?

前端 未结 2 1120
说谎
说谎 2021-02-02 03:32

Let\'s say we have a table with user comments. First-level comments have a reference to an article they are attached to. Deeper-level comments do not have this reference by desi

2条回答
  •  别那么骄傲
    2021-02-02 04:05

    For the most efficient way Quassnoi has written a series of articles on this subject.

    • Hierarchical queries in MySQL
    • Hierarchical queries in MySQL: adding level
    • Hierarchical queries in MySQL: adding ancestry chains.
    • Hierarchical queries in MySQL: finding leaves
    • Hierarchical queries in MySQL: finding loops

    I suggest you read the first article and adapt the examples to work with your specific table, but the crux is to make a function that can recurse over the rows you need to fetch. You probably also want the level (depth in the heirarchy) so the second article is probably also relevant too.

    The other articles may be useful if you need to make other types of queries on your data. He also has an article Adjacency list vs. nested sets: MySQL in which he compares highly optimized queries for both the adjacency model and the nested set model.

提交回复
热议问题