简体   繁体   中英

how to save a tree structure on DB

My Data has chapters and sub-chapters and items any item need to be under a chapter or sub-chapter. the chapters can be in many levels (chapter -> sub chapter -> sub sub chapter ...).

every chapter has a number, and i need to show the path for every item and chapter.

example :
---------------------
01 - chapter 1
01.0001 - item 1
01.001 - sub chapter 1
01.001.0001 - item 1
01.001.0002 - item 2
01.002 - sub chapter 2
01.003 - sub chapter 3
01.003.0001 - item 1

i think to save the chapter in one table and the items in another, because items have another properties (price,type...)

any chapter will have the parent Id.

any Thoughts?

Storing tree structures in DB systems is not a trivial task. The first thing which usually come to the mind is the ParentId. This solution is OK if you have small and fixed number of levels. The problem is that it is not so trivial to write a query for this type of table. You have to make a query recursive (for dynamic number of levels) or you have to write multiple joins (for fixed number of levels). I would recommend to use a varchar Path column instead of ParentId column. Lets see the example:

CREATE TABLE Chapters (    
   ID PRIMARY KEY,    
   Path VARCHAR(1000),     
   Title VARCHAR(255) NOT NULL          
);

Data example:

| Id         | Path        | Title           |
|------------|-------------|-----------------|
| 1          |     1/      | Chapter 1       | 
| 2          |     1/2/    | Chapter 1.1     |
| 3          |     1/2/3   | Chapter 1.1.1   |
| 4          |     1/4/    | Chapter 1.2     |
| 5          |     1/4/5   | Chapter 1.2.1   |
| 6          |     1/4/5/6 | Chapter 1.2.1.1 |

Then to query all descendants of Chapter 1 write:

SELECT *
FROM Chapters AS c
WHERE c.Path LIKE '1/' || '%';

To select all ancestors of Chapter 1.1.1 write:

SELECT *
FROM Chapters AS c
WHERE '1/2/3/' LIKE c.Path || '%';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM