Store multidimensional array in database: relational or multidimensional?

后端 未结 6 1778
栀梦
栀梦 2021-02-14 02:14

I have read numerous posts along the lines of multidimensional to single dimension, multidimensional database, and so on, but none of the answers helped. I did

6条回答
  •  傲寒
    傲寒 (楼主)
    2021-02-14 02:25

    For your scenario, I would suggest you to use Nested Sets Approach in PostgreSQL. It is XML tags based querying using Relational database.

    Performance

    If you index on lft and rgt columns, then you don't require recursive queries to get the data. Even though, the data seems huge, the retrieval will be very fast.

    Sample

    /*1A:
    2  AA:
    3    AAA
    4    AAC
    5  AB
    6  AE:
    7   AEA
    8   AEE:
    9     AEEB
    10B:
    */
    
    CREATE TABLE tree(id int, CELL varchar(4), lft int, rgt int);
        
    INSERT INTO tree
        ("id", CELL, "lft", "rgt")
    VALUES
        (1, 'A', 1, 9),
        (2, 'AA', 2, 4),
        (3, 'AAA', 3, 3),
        (4, 'AAC', 4, 4),
        (5, 'AB', 5, 5),
        (6, 'AE', 6, 9),
        (7, 'AEA', 7, 7),
        (8, 'AEE', 8, 8),
        (9, 'AEEB', 9, 9)
    ;
    
    
    SELECT  hc.*
    FROM    tree hp
    JOIN    tree hc
    ON      hc.lft BETWEEN hp.lft AND hp.rgt
    WHERE   hp.id = 2
    

    Demo

    Querying using Nested Sets approach

提交回复
热议问题