patternMinor
Symmetric self-referential many-to-many
Viewed 0 times
symmetricmanyreferentialself
Problem
I'm trying to model a hierarchy of categories where a category can have multiple parents ( an overlapping tree model as described in this book )
I have the following tables
and an index on [ parent_id, child_id ] for uniqueness
The issue with this setup is that
A can be parent of B, and B can be parent of A at the same time
Is there a way to specify a db constraint to avoid this or should I ensure it at the application level?
Thank you very much
I have the following tables
video_categories
int id
string name
video_category_links
int parent_id (foreign_key to video_categories.id)
int child_id (foreign_key to video_categories.id)and an index on [ parent_id, child_id ] for uniqueness
The issue with this setup is that
A can be parent of B, and B can be parent of A at the same time
Is there a way to specify a db constraint to avoid this or should I ensure it at the application level?
Thank you very much
Solution
I would define levels in the hierarchy:
I would propagate the parent and child levels into your link table:
video_categories
int id
int level
string nameI would propagate the parent and child levels into your link table:
video_category_links
int parent_id
int parent_level ((parent_id , parent_level) foreign_key to video_categories(id, level))
int child_id
int child_level((child_id , child_level) foreign_key to video_categories(id, level))
check(child_level > parent_level)Code Snippets
video_categories
int id
int level
string namevideo_category_links
int parent_id
int parent_level ((parent_id , parent_level) foreign_key to video_categories(id, level))
int child_id
int child_level((child_id , child_level) foreign_key to video_categories(id, level))
check(child_level > parent_level)Context
StackExchange Database Administrators Q#34532, answer score: 4
Revisions (0)
No revisions yet.