Middle — Middle+
How can you implement storage and display of a genealogical tree structure in a relational database?
sobes.tech AI
Answer from AI
To store and display a genealogical tree in a relational database, several approaches can be used:
- Adjacency List — each record contains a reference to its parent:
CREATE TABLE Person (
id INT PRIMARY KEY,
name VARCHAR(100),
parent_id INT NULL,
FOREIGN KEY (parent_id) REFERENCES Person(id)
);
-
Nested Sets — each node is assigned left and right values, allowing quick retrieval of subtrees.
-
Materialized Path — the path from the root to the node is stored as a string, for example, '1/4/6'.
To display the tree, records are usually selected recursively, starting from the root (parent_id = NULL), and the structure is built in the application memory.
In Java, recursive methods or SQL with recursive CTEs (if supported by the DBMS) can be used to obtain the hierarchy.