seedg
seedg

Reputation: 21975

Table which contains parent_id in same table while using a foreign key

I have a table which will contain various categories. The following is a minified table structure:

tb_categories
  category_id
  category_name
  category_parent_id

I created a foreign key constraint on category_parent_id on the category_id so data integrity can be held within the same table.

First question is, is it good practice to have a foreign key on the same table. From my way of thinking I am thinking that yes in such a case, it is a good practice.

Second question is, what is the best approach on how to store the global parent entity?

I came up with the following methods:

Method 1: category_parent_id can store nulls and the only null is the global parent category entitled All

Method 2: category_parent_id cannot store nulls and the global parrent ALL will contain its same category_id. Therefore, for only this category, both category_id and category_parent_id will be identical. Without nulls, I cannot insert this category_parent_id as 0 since 0 does not exist as a category_id

Method 3: Not having a global parent and there will be different 'parents'. For example, having Audio, Visual as parents and MP3, WMA as Audio's children and MPEG, AVI as Visual's children. Throughout this method, the same principles of methods 1 and 2 applies.

Method 4: This is the least method which I prefer which includes in not having this foreign key constraint and thus the global parent can be set to 0 which does not exist in any other category.

Any suggestions? As I am looking for the best practice and not something that 'just works'.

Upvotes: 0

Views: 430

Answers (1)

Nivas
Nivas

Reputation: 18354

It is normal to have a table refer itself. There are a lot of real world scenarios that need this situation (Employee -> Manager is a famous textbook example).

And, you will end up having a "global" parent whether it is a single global parent or multiple global parents. So you need to come up with an approach.

I prefer method 1 - an element without a parent will have no parent at all, because, well, it exactly realizes your business rule.

Having a 0 or referring self as parent will create problems when you have complex queries

Upvotes: 1

Related Questions