I'm putting together a database structure that can hold data for courses. Each course - will have several chapters and each chapter MAY have topics and each topic MAY have sub topics and so on.
This is sample data
Course - Accounts 1) Introduction to Accounts a) Basic Accounts 2) Financial Statements a) Income statement i) Depreciation b) Cash Flow Statement 3) Career as an accountant
Now each of these topics will have lecture notes associated with them. Now the way I'm thinking is incase of Chapter 1 - "Introduction" - the notes are going to be associated with the topic "Basic Accounts". But in chapter 2 - "Income Statement" wont have any notes but "Depreciation" is going to have notes. Now since Chapter 3 "Career as Accountant" does not have any sub topics - the notes are going to be associated directly with it.
This is just my way or organizing - I can enforce rules saying each chapter must have a subtopic so notes can be associated etc.
This is what I have so far
Table: Course course_id course_name Table: Topics topic_id parent_topic_id topic_name notes Table: Course_Topics course_id topic_id
So the sample data would appear as
Course_id | Course Name 1 Accounts Topic_id | Parent_topic_id | topic_name | notes 1 0 Introduction 2 1 Basic Accounts 3 0 Financial Statements 4 3 Income Statements 5 4 Depreciation Course_id | Topic_id 1 1 1 2 1 3 1 4 1 5
Here is what I'm looking for: 1) Is there a better way to design this - should I enforce stricter rules on how notes are associated with chapters or topics or sub topics
2) Secondly - given this data structure - if I wanted to pull all topics for a given course and display them in the chapter -> topic -> sub topic tree structure format. How would I do that. Should I just pull out all topics based on the course id and then in server side store them in data structures and organize them according to chapter/topic/subtopic wise or is there a cleaner way of doing it using sub queries.
Sorry for the long post - just wanted to clearly explain. Thanks for your time
****** EDIT ********
Thanks for all the answers guy. I came across this other approach of adding a lineage column and a deep column to the table.
The approach is explained here as "Flat table model done right" http://www.ferdychristant.com/blog/archive/DOMM-7QJPM7
What do you guys think of this approach.
Secondly - John raised a good point in his answer. How would I handle inserts in between. - Chapters (parent_id =0) Say if I want to insert a new chapter between chapter 1 and 2 - Topic (parent_id != 0 ) If I want to insert a new topic between any two existing topics
Should I have another column that maintains the order like 1,2,3 and then if I want to insert something in between chapters 1 and 2 - insert it with a value 1.1 or something like that - can the same column be used for topics as well.
Thanks again