Search code examples
mysqlsqloptimizationquery-optimization

Inter referencing vs external referencing


I have to design a table(s) with a parent and child relationship (category and sub category) Is it better to have two tables with the parent_id as a foreign key in the child table or having one table with parent_id as on column.


Solution

  • IF the main category and the subcategory have the same schema, one table.

    IF they have different schemas, two tables. An example of "doing this wrong" was a forum (or email) schema that tried to put Threads and Messages into the same table.

    The 'top' category can have its parent_id equal to 0 or NULL. The subcategories should have parent_id set to the id of the immediate parent. Note that this provides arbitrary nesting of categories (in a tree, no loops, etc).