-1

How do you design a database with sub topics, Data comes like this:

  • Topic 1

    • sub-topic 1.1
    • sub-topic 1.2
      • sub-topic 1.2.1
    • sub-topic 1.3
  • Topic 2

    • sub-topic 2.1
      • sub-topic 2.1.1
        • sub-topic 2.1.1.1

These topic could be nested. I created a 2 options.

  • First Option I could create a table for each topic and make it as 1 to many relationship, then query it with its parent topic_id.
Select
 *
From
 topics as T
JOINS " join on sub topics of sub topics here"
Where
 T.id = 1;

but then I will have a bunch of table of topics of sub-topics, and every time there's an additional sub-topic then the query will be updated. Then with this option I have to create a table on the "fly" if users want to create a sub-topic that's not created yet (not sure if its good idea to create a table via code?)

  • Second Option I could create a single table for all topics whether its the main topic of sub-topics of sub-topics, with the column parent_topic_id.

table will look like:

id title parent_topic_id
1 Topic 1 null
2 Topic 1.1 1
3 Topic 1.1.1 2
4 Topic 2 null
5 Topic 2.1 4

I'm still figuring out the query for this table. kinda confusing. Wanted to use this but i cant figure out the query for it.

This will be use internally, about 10K users, As of right now only 4 people can write/edit, 10k approximately will read the data.

Database used is mysql.

Shadow
  • 33,525
  • 10
  • 51
  • 64
aRtoo
  • 1,686
  • 2
  • 18
  • 38
  • 2
    Option 2 will be much simpler to maintain. To query it, you need a hierarchical/recursive query. There's tons of examples out there. – Andrew Aug 16 '23 at 15:47
  • 1
    You can deal with Hierarchies (i.e. your second option) using a [Recursive Common Table Expression](https://dev.mysql.com/doc/refman/8.0/en/with.html#common-table-expressions-recursive). There's a good article on this here: [MySQL 8.0 Labs: Recursive Common Table Expressions in MySQL (CTEs), Part Three - hierarchies](https://dev.mysql.com/blog-archive/mysql-8-0-labs-recursive-common-table-expressions-in-mysql-ctes-part-three-hierarchies/) – GarethD Aug 16 '23 at 15:49

0 Answers0