1

I am designing database for a blog, the blogs have categories and subcategories. Each blog has only one category (which may be category or subcategory).

I do not feel it's right to store the categories and subcategories in different database tables, so the problem is:

  1. must category and subcategory in same or different tables?

  2. How would I design the database tables to accomplish this?

W.K.S
  • 9,787
  • 15
  • 75
  • 122
Mathew
  • 137
  • 1
  • 4
  • 11

2 Answers2

3

Normal Approach

Table A: ID, CATEGORY
TABLE B: ID, CATEGORY_ID, SUBCATEGORY 

Just use 2 Tables.

Approach with subcategories related to more than one category

Table A: ID, CATEGORY
TABLE B: ID, SUBCATEGORY
TABLE C: ID, CATEGORY_ID, SUBCATEGORY_ID

Use this if you have subcategories added to more than one category.

Different Approach

TABLE A: ID, CATEGORY, SUBCATEGORY AS TEXT (SUBCATEGORIES as JSON List. e.g. ["SUB_1", "SUB_2"]) 

If you have a lot of subcategories added to more than one categories. In this case just save the SUBCATEGORY_ID in the list. Theen

TABLE A: ID, CATEGORY, SUBCATEGORY AS TEXT (SUBCATEGORIES_ID saved as JSON List. e.g. ["1","2"]) 
TABLE B: ID, SUBCATEGORY

It just depends if you want to search after subcategory in this case. If yes take the normal approach.

Kordi
  • 2,405
  • 1
  • 14
  • 13
  • some categories have no child so search can be based on subcategory or parent category, is the second approach is better in this case? If yes, is their another way without JSON? – Mathew Mar 05 '16 at 11:43
  • i would then take the different approach. You must save the subcategrories in a textfield, so json is a safe format to read and write. – Kordi Mar 05 '16 at 11:47
1

First, let me just point out that the StackExchange site for Database Administrators is more on-topic for DB design questions.

As @Kordi's answer already mentioned, there are essentially two approaches:

  1. Using one table per level you wish to make navigable. OR;

  2. Nesting your (sub-)categories all in one table.

Each of these have their own advantages/disadvantages. However, for a situation where you "have only one category (which can be category or subcategory[...])" I would say it's easier to use multiple tables.


However, since your question also specifies that you wish to only use one, you may want to take a look at this previous answer on hierarchical data in relational database.

Community
  • 1
  • 1
Tersosauros
  • 883
  • 1
  • 12
  • 22