0

I have a table structure for categories,

Each category can have many children, but can only be a child of one category.

I am deciding whether I should just add a parent_id column to the table, or whether I should add a reference table that just has the parent_id and child_id and maps them together.

If it is important a category can have no parent, in which case it is a root category.

The most common use cases for this table will be:

Selecting one category
Selecting all categories
Selecting all children of a category
Selecting the parent of a category
Selecting the child tree of a category

As far as I can tell there is no benefit of having a reference table for this setup? can anyone see any reason for using a reference table?

Hailwood
  • 89,623
  • 107
  • 270
  • 423

1 Answers1

1

If you add a reference table, you create an n:n relationship, which you don't want.

So just add a parent_id to the table. Make it nullable so you can define a category as the root.

Everything you want to select is quite easy, except for the child tree, but an extra table won't help with that. In Oracle you got connect by to select tree-like data, but MySQL unfortunatly doesn't support that, although alternative solutions are often requested and provided.

There are some obstacles:

  1. Since you cannot make parent_id unique (multiple childs can have the same parent), you will have to add a trigger to enforce only one category being the root, although maybe you can live without that check for the moment.

  2. You could theoretically create a loop: Make a the parent of b, b the parent of c, and c the parent of a. To check if this is the case, you should follow the path to the root. If on that path you'll find any category twice, you're in trouble. I think you could use a trigger to validate this as well, although maybe you can live without that check for the moment. It all depends on how you edit your data, but if you are going to query a full tree, you don't want to get into endless loops because of corrupt data.

Community
  • 1
  • 1
GolezTrol
  • 114,394
  • 18
  • 182
  • 210