Store multidimensional array in database: relational or multidimensional?

后端 未结 6 1771
栀梦
栀梦 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:40

    Performance

    As others have already mentioned, performance shouldn't be an issue as long as you use a suitable indexed primary key and ensure that relations use foreign keys. In general, an RDBMS is highly optimised to efficiently perform joins on indexed columns and referential integrity can also provide the advantage of preventing orphans. 100,000 may sound a lot of rows but this isn't going to stretch an RDBMS as long as the table structure and queries are well designed.

    Choice of RDBMS

    One factor in answering this question lies in choosing a database with the ability to perform a recursive query via a Common Table Expression (CTE), which can be very useful to keep the queries compact or essential if there are queries that do not limit the number of descendants being traversed.

    Since you've indicated that you are free to choose the RDBMS but it must run under Linux, I'm going to throw PostgreSQL out there as a suggestion since it has this feature and is freely available. (This choice is of course very subjective and there are advantages and disadvantages of each but a few other contenders I'd be tempted to rule out are MySQL since it doesn't currently support CTEs, MariaDB since it doesn't currently support *recursive* CTEs, SQL Server since it doesn't currently support Linux. Other possibilities such as Oracle may be dependent on budget / existing resources.)

    SQL

    Here's an example of the SQL you'd write to perform your first example of finding all the descendants of 'A':

    WITH RECURSIVE rcte AS (
       SELECT id, letters
       FROM cell 
       WHERE letters = 'A'
       UNION ALL
       SELECT c.id, c.letters
       FROM cell c
       INNER JOIN rcte r
       ON c.parent_cell_id = r.id
    )
    SELECT letters
    FROM rcte
    ORDER BY letters;
    

    Explanation

    The above SQL sets up a "Common Table Expression", i.e. a SELECT to run whenever its alias (in this case rcte) is referenced. The recursion happens because this is referenced within itself. The first part of the UNION picks the cell at the top of the hierarchy. Its descendants are all found by carrying on joining on children in the second part of the UNION until no further records are found.

    Demo

    The above query can be seen in action on the sample data here: http://rextester.com/HVY63888

提交回复
热议问题